SlideShare a Scribd company logo
1 of 3
Download to read offline
{Python} I keep running into error when fixing this code but I don't know what is wrong? It's able to
show two windows, but won't load the csv file into the window for a user to select options. My gui
should show a window that allows user to select country from file. Then it will print out a graph.
This is the code:
import sqlite3
import json
import matplotlib.pyplot as plt
import tkinter as tk
import socket
import csv
import pandas as pd
class User_Layer:
def __init__(self, root):
self.root = root
self.root.title("Country Selection")
self.country_label = tk.Label(self.root, text="Select a country:")
self.country_label.pack()
self.country_list = tk.Listbox(self.root)
self.country_list.pack()
self.countries = pd.read_csv('USAStates2020.csv')
['Country'].unique()
for country in self.countries:
self.country_list.insert(tk.END, country)
self.submit_button = tk.Button(self.root, text="Submit", command=self.submit)
self.submit_button.pack()
def submit(self):
selected_country = self.country_list.get(self.country_list.curselection())
business_layer = BusinessLayer()
business_layer.get_data(selected_country)
class BusinessLayer:
def __init__(self):
self.server_host = 'localhost'
self.server_port = 9999
def get_data(self, country):
sql_query = f"SELECT Year, Population FROM USAStates2020 WHERE Country = '{country}'
AND Year BETWEEN 1970 AND 2020"
data_layer = DataLayer(self.server_host, self.server_port)
data = data_layer.send_query(sql_query)
graphic_layer = GraphicLayer()
graphic_layer.plot(json.loads(data))
class DataLayer:
def __init__(self, host, port):
self.host = host
self.port = port
def send_query(self, query):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((self.host, self.port))
s.sendall(query.encode())
data = s.recv(1024).decode()
return data
class GraphicLayer:
def plot(self, data):
df = pd.DataFrame(data)
df['Year'] = pd.to_datetime(df['Year'], format='%Y')
# Plot the data using matplotlib
plt.plot(df['Year'], df['Population'])
plt.title('Population vs Year')
plt.xlabel('Year')
plt.ylabel('Population')
plt.show()
class ServerLayer:
def __init__(self, host, port):
self.host = host
self.port = port
def start(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((self.host, self.port))
s.listen()
print(f"Server listening on {self.host}:{self.port}")
while True:
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
query = conn.recv(1024).decode()
conn.execute(query)
results = conn.fetchall()
json_data = json.dumps(results)
conn.sendall(json_data.encode())
root = tk.Tk()
business_layer = __name__ == "__main__"
root = tk.Tk()
User_Layer = User_Layer(root)
root.mainloop()

More Related Content

Similar to Python I keep running into error when fixing this code but.pdf

in order to save data from access database and search from it in c# .pdf
in order to save data from access database and search from it in c# .pdfin order to save data from access database and search from it in c# .pdf
in order to save data from access database and search from it in c# .pdf
kalerottnerheissst52
 
bbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docx
bbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docxbbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docx
bbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docx
ikirkton
 
Quest 1 define a class batsman with the following specifications
Quest  1 define a class batsman with the following specificationsQuest  1 define a class batsman with the following specifications
Quest 1 define a class batsman with the following specifications
rajkumari873
 
ScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdf
ScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdfScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdf
ScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdf
alokindustries1
 
I doc packaging and mapping techniques.doc
I doc packaging and mapping techniques.docI doc packaging and mapping techniques.doc
I doc packaging and mapping techniques.doc
VERUS BRASIL
 
Please describe the following parts, out of an Python code for a Sto.pdf
Please describe the following parts, out of an Python code for a Sto.pdfPlease describe the following parts, out of an Python code for a Sto.pdf
Please describe the following parts, out of an Python code for a Sto.pdf
amarnathmahajansport
 
Previous weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docxPrevious weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docx
keilenettie
 

Similar to Python I keep running into error when fixing this code but.pdf (20)

Dojo1.0_Tutorials
Dojo1.0_TutorialsDojo1.0_Tutorials
Dojo1.0_Tutorials
 
Dash Intro.pdf
Dash Intro.pdfDash Intro.pdf
Dash Intro.pdf
 
in order to save data from access database and search from it in c# .pdf
in order to save data from access database and search from it in c# .pdfin order to save data from access database and search from it in c# .pdf
in order to save data from access database and search from it in c# .pdf
 
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeksBeginning direct3d gameprogramming05_thebasics_20160421_jintaeks
Beginning direct3d gameprogramming05_thebasics_20160421_jintaeks
 
Django wrapper
Django wrapperDjango wrapper
Django wrapper
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Chapter - 6.pptx
Chapter - 6.pptxChapter - 6.pptx
Chapter - 6.pptx
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutlet
 
bbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docx
bbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docxbbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docx
bbyopenApp_Code.DS_StorebbyopenApp_CodeVBCodeGoogleMaps.docx
 
Quest 1 define a class batsman with the following specifications
Quest  1 define a class batsman with the following specificationsQuest  1 define a class batsman with the following specifications
Quest 1 define a class batsman with the following specifications
 
ScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdf
ScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdfScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdf
ScenarioXYZ Corp. is a parent corporation with 2 handbag stores l.pdf
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
I doc packaging and mapping techniques.doc
I doc packaging and mapping techniques.docI doc packaging and mapping techniques.doc
I doc packaging and mapping techniques.doc
 
data binding.docx
data binding.docxdata binding.docx
data binding.docx
 
Using idoc method in lsmw
Using idoc method in lsmwUsing idoc method in lsmw
Using idoc method in lsmw
 
Pl sql using_xml
Pl sql using_xmlPl sql using_xml
Pl sql using_xml
 
Winforms
WinformsWinforms
Winforms
 
Please describe the following parts, out of an Python code for a Sto.pdf
Please describe the following parts, out of an Python code for a Sto.pdfPlease describe the following parts, out of an Python code for a Sto.pdf
Please describe the following parts, out of an Python code for a Sto.pdf
 
Previous weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docxPrevious weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docx
 

More from accumencomp

1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf
1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf
1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf
accumencomp
 
Aada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdf
Aada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdfAada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdf
Aada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdf
accumencomp
 
What is wrong with this code def plotCountryDensitiesdata.pdf
What is wrong with this code def plotCountryDensitiesdata.pdfWhat is wrong with this code def plotCountryDensitiesdata.pdf
What is wrong with this code def plotCountryDensitiesdata.pdf
accumencomp
 
The US Census Bureau estimates that there will be approxim.pdf
The US Census Bureau estimates that there will be approxim.pdfThe US Census Bureau estimates that there will be approxim.pdf
The US Census Bureau estimates that there will be approxim.pdf
accumencomp
 
n the very early days of computing images were produced usi.pdf
n the very early days of computing images were produced usi.pdfn the very early days of computing images were produced usi.pdf
n the very early days of computing images were produced usi.pdf
accumencomp
 

More from accumencomp (20)

Are large firms such as Walmart and Microsoft good or bad fo.pdf
Are large firms such as Walmart and Microsoft good or bad fo.pdfAre large firms such as Walmart and Microsoft good or bad fo.pdf
Are large firms such as Walmart and Microsoft good or bad fo.pdf
 
6 The investigative process by which geologists identify an.pdf
6 The investigative process by which geologists identify an.pdf6 The investigative process by which geologists identify an.pdf
6 The investigative process by which geologists identify an.pdf
 
Aadakilerden hangisi biyolojik bir zarn bileenlerini bir ara.pdf
Aadakilerden hangisi biyolojik bir zarn bileenlerini bir ara.pdfAadakilerden hangisi biyolojik bir zarn bileenlerini bir ara.pdf
Aadakilerden hangisi biyolojik bir zarn bileenlerini bir ara.pdf
 
1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf
1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf
1 Faiz oran euro cinsinden varlklarda yzde 7 dolar cinsin.pdf
 
Compute the following measures a Return on equity Net in.pdf
Compute the following measures a Return on equity  Net in.pdfCompute the following measures a Return on equity  Net in.pdf
Compute the following measures a Return on equity Net in.pdf
 
Consider a data of a numerical variable X given by the group.pdf
Consider a data of a numerical variable X given by the group.pdfConsider a data of a numerical variable X given by the group.pdf
Consider a data of a numerical variable X given by the group.pdf
 
Aada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdf
Aada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdfAada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdf
Aada bahsedilen Vaka almasndan aadaki sorular cevaplayn Nes.pdf
 
3102 Protect and monitor the physical facility and support.pdf
3102 Protect and monitor the physical facility and support.pdf3102 Protect and monitor the physical facility and support.pdf
3102 Protect and monitor the physical facility and support.pdf
 
Match the following incubation periods with their function .pdf
Match the following incubation periods with their function .pdfMatch the following incubation periods with their function .pdf
Match the following incubation periods with their function .pdf
 
What is wrong with this code def plotCountryDensitiesdata.pdf
What is wrong with this code def plotCountryDensitiesdata.pdfWhat is wrong with this code def plotCountryDensitiesdata.pdf
What is wrong with this code def plotCountryDensitiesdata.pdf
 
The US Census Bureau estimates that there will be approxim.pdf
The US Census Bureau estimates that there will be approxim.pdfThe US Census Bureau estimates that there will be approxim.pdf
The US Census Bureau estimates that there will be approxim.pdf
 
The following information is available for Oriole Corporatio.pdf
The following information is available for Oriole Corporatio.pdfThe following information is available for Oriole Corporatio.pdf
The following information is available for Oriole Corporatio.pdf
 
Santana Rey owner of Business Solutions decides to prepare.pdf
Santana Rey owner of Business Solutions decides to prepare.pdfSantana Rey owner of Business Solutions decides to prepare.pdf
Santana Rey owner of Business Solutions decides to prepare.pdf
 
QUESTION 4 Preduction data Poundt in proesss May 1 materi.pdf
QUESTION 4 Preduction data Poundt in proesss May 1 materi.pdfQUESTION 4 Preduction data Poundt in proesss May 1 materi.pdf
QUESTION 4 Preduction data Poundt in proesss May 1 materi.pdf
 
Please answer ASAP Ill rate thanks 1 There are a total .pdf
Please answer ASAP Ill rate thanks 1 There are a total .pdfPlease answer ASAP Ill rate thanks 1 There are a total .pdf
Please answer ASAP Ill rate thanks 1 There are a total .pdf
 
ou are analyzing the Victoria Inc VI stock Assume that .pdf
ou are analyzing the Victoria Inc VI stock Assume that .pdfou are analyzing the Victoria Inc VI stock Assume that .pdf
ou are analyzing the Victoria Inc VI stock Assume that .pdf
 
n the very early days of computing images were produced usi.pdf
n the very early days of computing images were produced usi.pdfn the very early days of computing images were produced usi.pdf
n the very early days of computing images were produced usi.pdf
 
In 2020 Pina Corporation had pretax financial income of 16.pdf
In 2020 Pina Corporation had pretax financial income of 16.pdfIn 2020 Pina Corporation had pretax financial income of 16.pdf
In 2020 Pina Corporation had pretax financial income of 16.pdf
 
Instructions 1 Refer back to the video assignments present.pdf
Instructions 1 Refer back to the video assignments present.pdfInstructions 1 Refer back to the video assignments present.pdf
Instructions 1 Refer back to the video assignments present.pdf
 
Islandia lkesindeki iletmeler ulusal ekonomi hakknda karam.pdf
Islandia lkesindeki iletmeler ulusal ekonomi hakknda karam.pdfIslandia lkesindeki iletmeler ulusal ekonomi hakknda karam.pdf
Islandia lkesindeki iletmeler ulusal ekonomi hakknda karam.pdf
 

Recently uploaded

Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MysoreMuleSoftMeetup
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 

Recently uploaded (20)

Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptxMichaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
Michaelis Menten Equation and Estimation Of Vmax and Tmax.pptx
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 

Python I keep running into error when fixing this code but.pdf

  • 1. {Python} I keep running into error when fixing this code but I don't know what is wrong? It's able to show two windows, but won't load the csv file into the window for a user to select options. My gui should show a window that allows user to select country from file. Then it will print out a graph. This is the code: import sqlite3 import json import matplotlib.pyplot as plt import tkinter as tk import socket import csv import pandas as pd class User_Layer: def __init__(self, root): self.root = root self.root.title("Country Selection") self.country_label = tk.Label(self.root, text="Select a country:") self.country_label.pack() self.country_list = tk.Listbox(self.root) self.country_list.pack() self.countries = pd.read_csv('USAStates2020.csv') ['Country'].unique() for country in self.countries: self.country_list.insert(tk.END, country) self.submit_button = tk.Button(self.root, text="Submit", command=self.submit) self.submit_button.pack() def submit(self): selected_country = self.country_list.get(self.country_list.curselection()) business_layer = BusinessLayer() business_layer.get_data(selected_country) class BusinessLayer: def __init__(self): self.server_host = 'localhost' self.server_port = 9999 def get_data(self, country): sql_query = f"SELECT Year, Population FROM USAStates2020 WHERE Country = '{country}' AND Year BETWEEN 1970 AND 2020" data_layer = DataLayer(self.server_host, self.server_port) data = data_layer.send_query(sql_query) graphic_layer = GraphicLayer() graphic_layer.plot(json.loads(data)) class DataLayer:
  • 2. def __init__(self, host, port): self.host = host self.port = port def send_query(self, query): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((self.host, self.port)) s.sendall(query.encode()) data = s.recv(1024).decode() return data class GraphicLayer: def plot(self, data): df = pd.DataFrame(data) df['Year'] = pd.to_datetime(df['Year'], format='%Y') # Plot the data using matplotlib plt.plot(df['Year'], df['Population']) plt.title('Population vs Year') plt.xlabel('Year') plt.ylabel('Population') plt.show() class ServerLayer: def __init__(self, host, port): self.host = host self.port = port def start(self): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((self.host, self.port)) s.listen() print(f"Server listening on {self.host}:{self.port}") while True: conn, addr = s.accept() with conn: print(f"Connected by {addr}") query = conn.recv(1024).decode() conn.execute(query) results = conn.fetchall() json_data = json.dumps(results) conn.sendall(json_data.encode()) root = tk.Tk() business_layer = __name__ == "__main__" root = tk.Tk() User_Layer = User_Layer(root)