i have an issue that i want to query from combo box value selected from sqllite database and show in graph,here is my code.I will be appreciate any one could help me.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import pandas as pd
import sqlite3
from sqlalchemy import create_engine
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
def imprt_data():
import_file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")],
title = "Choose a file")
df = pd.read_excel(import_file_path)
return df
def svetosql():
df=imprt_data()
engine = create_engine('sqlite:///save_pandas.db', echo=True)
sqlite_connection = engine.connect()
sqlite_table="Data"
df.to_sql(sqlite_table, sqlite_connection, if_exists='fail')
def sqlconection():
con=sqlite3.connect('save_pandas.db')
c = con.cursor()
return c
def callback_obj(event):
comboobject=event.widget.get()
return (comboobject)
def callback_rgn(event):
comboregion=event.widget.get()
return (comboregion)
root=tk.Tk()
root.title('Testing Tkinter Combobox With Sqllite')
root.geometry('500x500')
##---------Widget---------------
comboregion=ttk.Combobox(root,width=50 , height=20)
c=sqlconection()
for row in c.execute('SELECT DISTINCT Data.شهرستان from data '):
Query = [row[0] for row in c.fetchall()]
comboregion['values']=Query
comboregion.pack( ipadx=2, ipady=2 )
selectvalueregion=comboregion.bind("<<ComboboxSelected>>", callback_rgn)
#------------------------
comboobject=ttk.Combobox(root,width=50 , height=20)
c=sqlconection()
for row in c.execute('SELECT DISTINCT from Data '):
Query = [member[0] for member in c.description]
comboobject['values']=Query
comboobject.pack( ipadx=2, ipady=2 )
selectvalueobject=comboobject.bind("<<ComboboxSelected>>", callback_obj)
for row in c.execute('SELECT DISTINCT * from Data WHERE region LIKE ? ;' , (selectvalueobject,)):
Q = [row[0] for row in c.fetchall()]
print(Q)
#------------------------
f = Figure(figsize=(5,5), dpi=80)
a = f.add_subplot(111)
a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
canvas = FigureCanvasTkAgg(f, root)
canvas.draw()
canvas.get_tk_widget().pack(ipadx=2, ipady=2)
root.mainloop()
the graph has some data only for show,but i want to get data from combo box and then make query from database and after that show in graph.
if any one want to get database ,please leave comments.
Related
I try to make a line graph with python and the graph only appears a little in the end of the canvas in the GUI. The data that should be paper was taken from the database.
enter image description here
import sqlite3 ###----------------Connecting to the database-------------#####
DB = sqlite3.connect ("personal_project.db")
CURSOR = DB.cursor()
###----------------create the SQL command to create the table and save data-------------######
COMMAND1 = """CREATE TABLE IF NOT EXISTS
balance (
UserID INTEGER PRIMARY KEY,
Date TEXT,
Amount TEXT,
Descriotion)"""
CURSOR.execute(COMMAND1)
from tkinter import *
from tkinter import messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
###----------------Create the window-------------#####
main_WINDOW = Tk()
main_WINDOW.title("Study App")
main_WINDOW.geometry("1940x1080")#width*length
main_WINDOW.configure(bg="#ffffff")
###------Show Information Using Graph-------###
graquery = '''SELECT Date, Amount FROM balance'''
CURSOR.execute(graquery)
graresults = CURSOR.fetchall()
Date = [result[0] for result in graresults]
Amount = [result[1] for result in graresults]
figure = plt.figure()
plt.plot(Date, Amount)
plt.xlabel('Date')
plt.ylabel('Amount')
plt.title('Balance graph Graph')
gracanvas = Canvas(main_WINDOW, width=1070, height=452)
gracanvas.pack()
gracanvas.place(x=356, y=270)
figure_canvas = FigureCanvasTkAgg(figure, gracanvas)
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget())
Consider this code:
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget())
The create_window method by default centers the window at the given coordinate, which is what your image looks like. If you want the top-left corner of the window to be at 0,0, specify anchor="nw" so that the northwest corner of the window is at the given coordinate.
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget(), anchor="nw")
# ^^^^^^^^^^^
I try to make a line graph with python and the graph only appears a half of the canvas and the rest is only black in the GUI. The data that should be appear was taken from the database.
###----------------Connecting to the database-------------#####
import sqlite3
DB = sqlite3.connect ("personal_project.db")
CURSOR = DB.cursor()
###----------------create the SQL command to create the table and save data-------------######
COMMAND1 = """CREATE TABLE IF NOT EXISTS
balance (
UserID INTEGER PRIMARY KEY,
Date TEXT,
Amount TEXT,
Descriotion)"""
CURSOR.execute(COMMAND1)
from tkinter import *
from tkinter import messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
###----------------Create the window-------------#####
main_WINDOW = Tk()
main_WINDOW.title("Study App")
main_WINDOW.geometry("1940x1080")#width*length
main_WINDOW.configure(bg="#ffffff")
###------Show Information Using Graph-------###
graquery = '''SELECT Date, Amount FROM balance'''
CURSOR.execute(graquery)
graresults = CURSOR.fetchall()
Date = [result[0] for result in graresults]
Amount = [result[1] for result in graresults]
figure = plt.figure()
plt.plot(Date, Amount)
plt.xlabel('Date')
plt.ylabel('Amount')
plt.title('Balance graph Graph')
gracanvas = Canvas(main_WINDOW, width=1070, height=452)
gracanvas.place(x=356, y=270)
figure_canvas = FigureCanvasTkAgg(figure, gracanvas)
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget(), anchor="nw")
main_WINDOW.mainloop()
good evening for all
for a project I have to read and filter a big table (more than 50k lines) using tkinter for this I created a progressbar which is activated while the application calls the filter function in the background.
the problem is that my progress bar does not move i tried with the threading library but nothing changed. does anyone have a solution?
if you also have an idea to insert the lines more quickly in the treeview it would really help me a lot
import tkinter as tk
from tkinter import *
from tkinter import ttk
import numpy as np
import pandas as pd
from threading import *
import time
class Application(tk.Tk):
def __init__(self):
Tk.__init__(self)
self.title("table manipulation")
# I create a random table with 50 rows
self.my_table=pd.DataFrame(np.random.rand(50,4))
#I create a Progressbar
self.progressbar=ttk.Progressbar(self,orient='horizontal',mode='indeterminate',length=280,value=0)
self.progressbar.pack(fill=X)
#I create a single filter for the example
self.filter_frame = Frame(self)
self.filter_frame.pack()
self.create_filter()
#I create a table with tkinter treeview
self.table_frame = Frame(self)
self.table_frame.pack()
self.tree = ttk.Treeview(self.table_frame, show='headings')
self.create_table()
def create_filter(self):
#for example i create one filter
self.my_filter=ttk.Combobox(self.filter_frame,values=[''] +list(set(self.my_table.values.tolist()[0])) , state="readonly")
self.my_filter.pack()
self.my_filter.bind('<<ComboboxSelected>>', self.threading)
def create_table(self):
self.tree["columns"] =self.my_table.columns.values.tolist()
self.tree.pack(expand=TRUE, fill=X)
for i in self.my_table.columns.values.tolist():
self.tree.column(i, anchor="w")
self.tree.heading(i, text=i, anchor="w")
for n in range(len(self.my_table)):
self.tree.insert("", "end", text=n, values=self.my_table.values.tolist()[n])
def filter_function(self,*args):
for n in self.tree.get_children():
time.sleep(1) #to check if my progressbar moves
if self.tree.item(n)['values'][0]!=self.my_filter.get():
self.tree.delete(n)
def threading(self,*args):
self.progressbar.start()
t1=Thread(target=self.filter_function())
t1.start()
self.progressbar.stop()
Application().mainloop()
I found the solution for those who need it
import tkinter as tk
from tkinter import *
from tkinter import ttk
import numpy as np
import pandas as pd
import threading
import time
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("table manipulation")
# I create a random table with 10 rows
self.my_table=pd.DataFrame(np.random.rand(10,4))
#I create a Progressbar
self.progressbar=ttk.Progressbar(self,orient='horizontal',mode='indeterminate',length=280,value=0)
self.progressbar.pack()
#I create a single filter for the example
self.filter_frame = tk.Frame(self)
self.filter_frame.pack()
self.create_filter()
#I create a table with tkinter treeview
self.table_frame = tk.Frame(self)
self.table_frame.pack()
self.treeview = ttk.Treeview(self.table_frame, show='headings')
threading.Thread(target=self.create_table() , daemon=True).start()
def create_filter(self):
#for example i create one filter
self.my_filter=ttk.Combobox(self.filter_frame,values=[''] +list(set(self.my_table.values.tolist()[0])) , state="readonly")
self.my_filter.pack()
self.my_filter.bind('<<ComboboxSelected>>', self.threading)
def create_table(self):
self.treeview["columns"] =self.my_table.columns.values.tolist()
self.treeview.pack()
for i in self.my_table.columns.values.tolist():
self.treeview.column(i, anchor="w")
self.treeview.heading(i, text=i, anchor="w")
for n in range(len(self.my_table)):
self.treeview.insert("", "end", text=n, values=self.my_table.values.tolist()[n])
def test(self):
for n in range(200):
time.sleep(1) #to check if my progressbar moves
def filter_function(self,*args):
self.progressbar.start()
for n in self.treeview.get_children():
time.sleep(1) #to check if my progressbar moves
if self.treeview.item(n)['values'][0]!=self.my_filter.get():
self.treeview.delete(n)
self.progressbar.stop()
def threading(self,*args):
threading.Thread(target=self.filter_function , daemon=True).start()
Application().mainloop()
Its Not Giving Any Errors Just Not Showing Up If it seems a little choppy sorry been getting frustrated but literally everything works no errors at all it even enters the camper id but no name someone please help, thank you, and dont down this please been getting allot of strikes even though most of the people dont actually read the code [FIXED]
import tkinter
from tkinter import *
import random
from random import randint
import sqlite3
from sqlite3 import *
#creating screen
page = tkinter.Tk()
#naming screen
page.title('Camp Sign-up')
#setting screen size
page.geometry("1000x500")
#creating text
Title = tkinter.Label(page, text='Registration', font=('arial') ).pack()
FullName = tkinter.Label(page, text='Full Name:', font=('arial')).place(x=110, y=50)
full = StringVar()
FullNameValue = Entry(page, textvar=full, width=25,).place(x=200, y=53)
CamperID = random.randint(100000, 1000000)
#Database
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
def createtable():
c.execute("""CREATE TABLE Registration (
CampID INT,
full TEXT,
)""")
try:
createtable()
except:
sqlite3.OperationalError
#button
def buttonclick():
#heres where you lnk where you want your info to go
FullNameValu= full.get()
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
c.execute("INSERT INTO Registration(CampID, full)VALUES(?, ?)",(CamperID, FullNameValu))
conn.commit()
#button
work = Button(page, text='Submit', width=10, height=2, bg='lightgrey',
command=buttonclick()).place(x=475, y=450)
#heres where you execute your close files commands
conn.commit()
c.close()
conn.close()
#ending code never put this above anything
page.mainloop()
Your buttonclick() run as soon as you start the program cause have done this way command=buttonclick() which suppose to be command=buttonclick. Also your creation of your database is not good have changed that and refactor your all code.
import tkinter
from tkinter import *
import random
from random import randint
import sqlite3
from sqlite3 import *
# THIS IS CREATING DATABASE
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS Registration (CampID INT, full TEXT)""")
conn.commit()
conn.close()
#button
def buttonclick():
#heres where you lnk where you want your info to go
FullNameValu= full.get()
# generating the camp id
CamperID = random.randint(100000, 1000000)
conn = sqlite3.connect('YouthCamp.db')
c = conn.cursor()
c.execute("INSERT INTO Registration(CampID, full)VALUES(?, ?)",(CamperID, FullNameValu))
conn.commit()
conn.close()
print("records inserted")
#creating screen
page = tkinter.Tk()
#naming screen
page.title('Camp Sign-up')
#setting screen size
page.geometry("1000x500")
#creating text
Title = tkinter.Label(page, text='Registration', font=('arial') )
Title.pack()
FullName = tkinter.Label(page, text='Full Name:', font=('arial'))
FullName.place(x=110, y=50)
full = StringVar()
FullNameValue = Entry(page, textvar=full, width=25,)
FullNameValue.place(x=200, y=53)
#button
work = Button(page, text='Submit', width=10, height=2, bg='lightgrey',
command=buttonclick).place(x=475, y=450)
page.mainloop()
I am trying to have two ttk comboboxes that fetch data from a sqlite database. I managed to be able and list items in one combobox named divisiondropmenu using the combo_division() function. Now I am trying to do a similar thing for the second combobox named productdropmenu, but the list would need to be narrowed down based on the first selected item in combobox named divisiondropmenu.
For the SQL query to pass the needed information for the second combobox I was thinking of something of this sort:
'SELECT * FROM productname WHERE divisionname=?', (function_name())
Code for the two comboboxes so far:
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import sqlite3
def combo_division():
conn = sqlite3.connect('anglingdatabase.db')
cursor = conn.cursor()
cursor.execute('SELECT divisionname FROM productdivision')
data = []
for row in cursor.fetchall():
data.append(row[0])
return data
root = Tk()
root.title("Random Window Title")
root.geometry('1280x720')
rows = 0
while rows < 50:
root.rowconfigure(rows, weight=1)
root.columnconfigure(rows, weight=1)
rows += 1
divisiondropmenu = ttk.Combobox(root)
divisiondropmenu['values'] = combo_division()
divisiondropmenu.bind('<<ComboboxSelected>>', selecteddivision)
divisiondropmenu.grid(row=1, column=2, sticky='NESW')
productdropmenu = ttk.Combobox(root)
productdropmenu['values'] = combo_product()
productdropmenu.grid(row=2, column=2, sticky='NESW')
root.mainloop()
data = combo_division()
example_sql = ''' SELECT * FROM tablename WHERE division in ('{}') '''.format("','".join(data))
You could build the actual SQL dynamically provided that the data was never user input (to avoid SQL injection).