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.
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())
Related
How do I make the checkboxes stay ticked? I want it to save to a local database. Here is where I gave up:
import sqlite3
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
from sqlite3 import *
import json
box = Tk()
box.geometry('600x450')
box.title('November Assesment Study List')
box.resizable(False,False)
checkbox1 = tk.StringVar()
checkbox2 = tk.StringVar()
checkbox3 = tk.StringVar()
checkboxes = []
sql_as_text = json.dumps(checkboxes)
checkboxes.append(checkbox1)
checkboxes.append(checkbox2)
checkboxes.append(checkbox3)
connection = sqlite3.connect("Checkedboxes.db")
cursor = connection.cursor()
# cursor.execute("CREATE TABLE Valees (checked integer)")
# query = "INSERT INTO Valees (checked) VALUES (?)"
cursor.execute("INSERT INTO Valees (checked) VALUES )")
# cursor.execute(query, [sql_as_text])
r = cursor.fetchall()
def btn1_checked():
w = checkbox1.get()
checkboxes.append(w)
print(str(checkboxes))
print(r)
def openNewWindow1():
newWindow = Toplevel(box)
newWindow.title("Maths")
newWindow.geometry("400x200")
ttk.Checkbutton(newWindow, text= 'Algebra', command=btn1_checked, variable=checkbox1, onvalue='1', offvalue='0').pack()
ttk.Checkbutton(newWindow, text= 'Calculus', onvalue='1', offvalue='0').pack()
ttk.Checkbutton(newWindow, text= 'Trig', onvalue='1', offvalue='0').pack()
btn = Button(box,
text ="Maths",
command = openNewWindow1)
btn.pack(pady = 10)
cursor.close()
connection.commit()
connection.close()
box.mainloop()
You could also use a local file. Would be a different approach, but then there is no need to install mysql first.
But you were right. You need to store the state of the checkbox somewhere.
checkbox1 = True
f = open("file.txt", "a") # "a" will append to the end of the file.
f.write("checkbox1=" + str(checkbox1) + "\n") # "\n" will create a new paragraph
f.close()
# open read the file
f = open("file.txt", "r")
print(f.read())
Something like this ;)
I'm trying to make a python project which is an employee management system where i'm using various libraries of python like tkinter, sqlite3 (to connect the database), matplotlib. In the proposed project, we can add, view, update, delete and plot graphs for the employees. The issues i'm facing are towards the graphs. The code for the graphs is as follows
from tkinter import *
from tkinter.messagebox import *
from tkinter.scrolledtext import *
from sqlite3 import *
import matplotlib.pyplot as plt
def graphback():
graph_window.deiconify()
main_window.withdraw
def graph():
con = None
try:
con = connect(project.db)
cursor = con.cursor()
sql = "select * from employee"
cursor.execute(sql)
data = cursor.fetchall()
name = []
salary = []
plt.plot(name, salary)
plt.title("Highest Salaried Employee")
plt.show
except Exception as e:
showerror("issue ", e)
con.rollback()
finally:
if con is not None:
con.close()
def mgraph():
main_window.deiconify()
graph_window.withdraw()
I can't get the graph when i run the code. What should i do to run the code?
You missed the parenthesis around plt.show, otherwise you're not calling the function.
Change it to
from tkinter import *
from tkinter.messagebox import *
from tkinter.scrolledtext import *
from sqlite3 import *
import matplotlib.pyplot as plt
def graphback():
graph_window.deiconify()
main_window.withdraw
def graph():
con = None
try:
con = connect(project.db)
cursor = con.cursor()
sql = "select * from employee"
cursor.execute(sql)
data = cursor.fetchall()
name = []
salary = []
plt.plot(name, salary)
plt.title("Highest Salaried Employee")
# SEE HERE
plt.show()
except Exception as e:
showerror("issue ", e)
con.rollback()
finally:
if con is not None:
con.close()
def mgraph():
main_window.deiconify()
graph_window.withdraw()
I am trying to read the latest row from a table and plot the graph using animate and matplotlib in python. The table gets updated every 1 second with a new value. I need to simulate the graph by live plotting the values.
However, when I use animate function with an interval of 1 second, I get the same value for every interval fetch.
I am adding the code for your reference. Please let me know what I am missing. The same code is working good when I use a flat file instead of MySql table.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import mysql.connector
import pandas as pd
style.use('fivethirtyeight')
mydb = mysql.connector.connect(
host="xxxxxxxxxx",
user="xxxxx",
passwd="xxxxxxx",
database="sakila"
)
fig = plt.figure(figsize=(8,5))
ax = plt.subplot2grid((1,1), (0,0))
plt.ion()
cursor = mydb.cursor()
def animate(i):
df = pd.read_sql("SELECT * FROM DATA_TEST ORDER BY ID DESC LIMIT 1", mydb)
y = df["VALUE"]
x = df["ID"]
xs = []
ys = []
xs.append(x)
ys.append(float(y)*100)
ax.clear()
ax.plot(xs,ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
## TESTING CURSOR IN FOR LOOP
import mysql.connector
import pandas as pd
import time
mydb = mysql.connector.connect(
host="xxxxxxx",
user="xxxx",
passwd="xxxxxx",
database="xxxxx"
)
for i in range(10):
cursor = mydb.cursor()
cursor.execute("SELECT * FROM DATA_TEST ORDER BY ID DESC LIMIT 1")
result = cursor.fetchall()
print("Total rows are: ", len(result))
for j in result:
print(j[0])
print(j[1])
time.sleep(10)
cursor.close()
Empty entries filled in MySQL tables (Python + Tkinter)
Having a problem of data entry in MySQL. At the time of entry it don't take any value from me or
user. And one more thing I want to add multiple pages. But how can I make button to submit the value and direct to page 2. please if anyone know then please me.
Thank you
Here he the table which is completely empty.
from tkinter import *
import mysql.connector
from PIL import Image,ImageTk
m=Tk()
button_bg='#FF9200'
button_fg='#fff'
active_button_fg='#FF9200'
active_button_bg='#fff'
def tkinter_setup():
m.geometry('1024x720')
def database_connectivity():
FullName=StringVar()
CollegeName=StringVar()
Email = StringVar()
Password=IntVar()
CGPA= IntVar()
fullName=FullName.get()
collegeName=CollegeName.get()
email=Email.get()
password=Password.get()
cgpa=CGPA.get()
mydb = mysql.connector.connect(host="localhost", user="root", passwd="ashu12",database='mySchool')
cursor=mydb.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS Student (FullName TEXT,CollegeName TEXT,Email TEXT,Password INT,CGPA INT)')
cursor.execute('INSERT INTO Student (FullName,CollegeName,Email,Password,CGPA) VALUES(%s,%s,%s,%s,%s)',(fullName,collegeName,email,password,cgpa))
mydb.commit()
def page2():
entry7 = Entry(m,width=70)
entry7.place(x=0,y=30)
entry7.insert(0,'Full Name')
m.mainloop()
def page1():
Image_open=Image.open("1.png")
image=ImageTk.PhotoImage(Image_open)
logo=Label(m,image=image)
logo.place(x=0,y=0,bordermode="outside")
entry1 = Entry(m,textvar='FullName',font="Ubuntu")
entry1.place(height=45,width=397,x=145,y=154)
entry1 = Entry(m,width=42,textvar='Collegename',font="Ubuntu")
entry1.place(height=45,width=397,x=145,y=210)
entry1 = Entry(m,width=42,textvar='Email',font="Ubuntu")
entry1.place(height=45,width=397,x=145,y=266)
entry1 = Entry(m,width=42,textvar='Password',font="Ubuntu")
entry1.place(height=45,width=397,x=145,y=322)
entry1 = Entry(m,width=42,textvar='CGPA',font="Ubuntu")
entry1.place(height=45,width=397,x=145,y=377)
button = Button(m,text='Registration' , bg=button_bg,foreground=button_fg,activebackground=active_button_bg,activeforeground=active_button_fg,command=page2 )
button.place(height=47, width=399 ,x=144,y=476)
m.mainloop()
tkinter_setup()
database_connectivity()
page1()
page2()
import time
import subprocess
from tkinter import *
from w1thermsensor import W1ThermSensor
import time
import datetime
import sqlite3
root = Tk()
id = 1
conn = sqlite3.connect('temp_sensor2.db')
c = conn.cursor()
sensor = W1ThermSensor()
temperature = sensor.get_temperature()
t = int(time.time())
date = str (datetime.datetime.fromtimestamp(t).strftime('%d-%m-%Y %H:%M:%S'))
global tempLabel1
def get_temp(period_ms):
temperature = sensor.get_temperature()
tempLabel1['text'] = temperature
tempLabel1.after(period_ms, get_temp, period_ms)
c.execute('''INSERT INTO datetemp VALUES (?, ?, ?)''',(id, date, temperature));
conn.commit()
root.title('Temperature')
tempLabel2 = Label(root, text="Temperature is ")
tempLabel2.pack()
tempLabel1 = Label(root, width=25)
tempLabel1.pack()
get_temp(1000)
root.mainloop()
I have a program here that monitors temperature and automatically updates in a tkinter label. I also wish to have it update a SQLite DB, however it enters multiple entries into the table with the exact same datestamp (although temperature reading will be different). Any ideas would be appreciated!
t = int(time.time())
date = str (datetime.datetime.fromtimestamp(t).strftime('%d-%m-%Y %H:%M:%S'))
These two lines of code run once, when your program starts up, and the date variable never changes after that.
If you move these lines inside the get_temp() function, then it will use the current timestamp.