Automatic calculation from treeview values - tkinter python - python

Please help. I am working on a table where the user enters the beginning of working hours Od and end of working hours Do.
The number of hours spent at work should then be calculated automatically. But now it doesn't count for me and I don't know where my mistake is anymore.
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkcalendar import DateEntry
from tkinter.filedialog import asksaveasfile
from tkinter.messagebox import showinfo,askquestion
from tkinter import filedialog
import sys
import csv
# základ okna ###############################################
okno = tk.Tk()
okno.title("Evidence pracovní doby")
# menubar ###############################################
def openfile():
"""Položka "Otevřít" v menu "Soubor" """
with open("new.csv") as myfile:
csvread = csv.reader(myfile, delimiter=",")
for row in csvread:
tabulka.insert("", "end", values=row)
def savefile():
""" Položka "Uložit" v menu "Soubor" """
with open("new.csv", "w", newline="") as myfile:
csvwriter = csv.writer(myfile, delimiter=",")
for row_id in tabulka.get_children():
row = tabulka.item(row_id)["values"]
csvwriter.writerow(row)
showinfo("Uložení", "Uložení proběhlo v pořádku.")
def info_menu():
""" Položka "Info" v menu"""
info_okno = tk.Toplevel()
info_okno.title("Info")
Label(info_okno, text="WORK TIME v0.1", font="bold").grid(row=1, column=0, sticky="we", pady=5, padx=5)
Label(info_okno, text="Jakub Kolář\nkolarkuba#gmail.com\n2022").grid(row=2, column=0, sticky="we", pady=5, padx=5)
close_button = Button(info_okno,text = "Zavřít",command=lambda:info_okno.destroy()).grid(row=3, column=0, pady=5)
mb = Menu(okno)
file_menu = Menu(mb, tearoff=0)
file_menu.add_command(label="Otevřít poslední", command=openfile)
file_menu.add_command(label="Uložit", command=savefile)
file_menu.add_separator()
file_menu.add_command(label="Zavřít", command=lambda:okno.destroy())
mb.add_cascade(label="Soubor", menu=file_menu)
mb.add_command(label="Info", command=info_menu)
okno.config(menu=mb)
# Jméno ###############################################
Label(okno, text="Jméno").grid(row=2, column=0, sticky="w", padx=5)
jmeno = Entry(okno)
jmeno.insert(10,"")
jmeno.grid(row=3, column=0, sticky="w", padx=5)
# Součet ###############################################
Label(okno, text="Celkem hodin").grid(row=2, column=0, sticky="e", padx=5)
h = 0 # součet všech hodin
soucet = Entry(okno, width=5)
soucet.insert(10,h)
soucet.grid(row=3, column=0, sticky="e", padx=5, pady=5)
# tabulka ###############################################
tabulka = ttk.Treeview(okno)
tabulka.grid(row=4, column=0, sticky="w", padx=5)
# nastavení sloupců
tabulka["columns"] = ("Datum", "Od", "Do", "Hodin", "Misto", "Poznamka")
tabulka.column("#0", width=0, stretch=NO)
tabulka.column("Datum", anchor=CENTER, width=80)
tabulka.column("Od", anchor=CENTER, width=80)
tabulka.column("Do", anchor=CENTER, width=80)
tabulka.column("Hodin", anchor=CENTER, width=80)
tabulka.column("Misto", anchor=CENTER, width=150)
tabulka.column("Poznamka", anchor=CENTER, width=80)
# nastavení popisků sloupců
tabulka.heading("#0",text="",anchor=CENTER)
tabulka.heading("Datum",text="Datum",anchor=CENTER)
tabulka.heading("Od",text="Od",anchor=CENTER)
tabulka.heading("Do",text="Do",anchor=CENTER)
tabulka.heading("Hodin",text="Hodin",anchor=CENTER)
tabulka.heading("Misto",text="Místo",anchor=CENTER)
tabulka.heading("Poznamka",text="Poznámka",anchor=CENTER)
# data ###############################################
data = []
global count
count = 1
for zaznam in data:
tabulka.insert(parent='', index="end", iid=count, text="", values=(zaznam[0],
zaznam[1], zaznam[2], zaznam[3], zaznam[4], zaznam[5]))
count += 1
# Rámec vkládacích polí ###############################################
Input_frame = Frame(okno)
Input_frame.grid(row=5, column=0)
# Popisky vkládacích polí
Datum = Label(Input_frame,text="Datum")
Datum.grid(row=0,column=0)
Od = Label(Input_frame,text="Od")
Od.grid(row=0,column=1)
Do = Label(Input_frame,text="Do")
Do.grid(row=0,column=2)
Hodin = Label(Input_frame,text="")
Hodin.grid(row=0, column=3)
Misto = Label(Input_frame,text="Místo")
Misto.grid(row=0,column=4)
Poznamka = Label(Input_frame,text="Poznámka")
Poznamka.grid(row=0,column=5)
# vkládací pole
Datum_entry = DateEntry(Input_frame, width=8)
Datum_entry.grid(row=1,column=0)
Od_entry = Entry(Input_frame, width=8)
Od_entry.grid(row=1,column=1)
Do_entry = Entry(Input_frame, width=8)
Do_entry.grid(row=1,column=2)
Hodin_entry = Entry(width=0)
Misto_entry = Entry(Input_frame, width=24)
Misto_entry.grid(row=1,column=4)
Poznamka_entry = Entry(Input_frame, width=15)
Poznamka_entry.grid(row=1,column=5)
# Rámec tlačítek ###############################################
Button_frame = Frame(okno)
Button_frame.grid(row=6, column=0)
def input_record():
""" nastavení vyčítaní vkládacích polí"""
global count
global h
global citac_hodin
tabulka.insert(
parent="",
index="end",
iid = count,
text="",
values=(
Datum_entry.get(),
Od_entry.get(),
Od_entry.get(),
Hodin_entry.get(),
Misto_entry.get(),
Poznamka_entry.get()))
count += 1
Datum_entry.delete(0,END)
Od_entry.delete(0,END)
Do_entry.delete(0,END)
Misto_entry.delete(0,END)
Poznamka_entry.delete(0,END)
def delete():
""" Smazání vybraných dat z tabulky"""
selected_item = tabulka.selection()[0]
tabulka.delete(selected_item)
# button "Vložit záznam"
butt_plus = PhotoImage(file="/home/jakub/GitHub/Work_time/program/plus.png")
Input_button = Button(Button_frame, command=input_record, image=butt_plus,
relief="flat").grid(row=0, column=0, pady=5)
# button "Smazat záznam"
butt_minus = PhotoImage(file="/home/jakub/GitHub/Work_time/program/minus.png")
delete_button = Button(Button_frame, command=delete, image=butt_minus,
relief="flat").grid(row=0, column=1, pady=5)
# metoda hlavního okna mainloop, udržuje okno otevřené
okno.mainloop()

As it was mentioned in comments, there was no code for working_hours calculation in Your example.
Basically what You have to do is to track changes of Od and Do and calculate difference between them.
You can do that by passing textvariable into Entry and then trace any change of that variable.
For simplicity, I made an example only for full hours (no minutes) and valid hours are between 0-24. If those conditions are not met working_hours are set to 0. Of course You can then modify it to work with any other time format You need. I also trimmed Your example to necessary minimum.
Also, as this is Your first question. Stick with only english, especially for comments in Your code. You make it easier for others to help You.
import tkinter as tk
from tkinter import *
# základ okna ###############################################
okno = tk.Tk()
okno.title("Evidence pracovní doby")
# Rámec vkládacích polí ###############################################
Input_frame = Frame(okno)
Input_frame.grid(row=2, column=10)
# Popisky vkládacích polí
Od = Label(Input_frame, text="Od")
Od.grid(row=0, column=0)
Do = Label(Input_frame, text="Do")
Do.grid(row=0, column=1)
Hodin = Label(Input_frame, text="Hodin")
Hodin.grid(row=0, column=2)
# vkládací pole
Od_var = IntVar(value=9)
Od_entry = Entry(Input_frame, width=8, textvariable=Od_var)
Od_entry.grid(row=1, column=0)
Do_var = IntVar(value=17)
Do_entry = Entry(Input_frame, width=8, textvariable=Do_var)
Do_entry.grid(row=1, column=1)
Hodin_var = IntVar(value=8)
Hodin_entry = Entry(Input_frame, width=8, textvariable=Hodin_var, state="readonly")
Hodin_entry.grid(row=1, column=2)
def count_working_hours(*args):
global Od_var, Do_var, Hodin_var
try:
# Get Od and Do values (should be integer)
od = Od_var.get()
do = Do_var.get()
if not (0 <= od <= 24) or not (0 <= do <= 24) or od > do:
# invalid input: either od or do is not valid hours or od is higher than do
raise ArithmeticError
working_hours = do - od
except (TclError, ArithmeticError):
# In case of invalid input, set working hours to 0
working_hours = 0
finally:
# Set working hours
Hodin_var.set(working_hours)
# Trace Od and Do, call count_working_hours on change
Od_var.trace("w", count_working_hours)
Do_var.trace("w", count_working_hours)
# metoda hlavního okna mainloop, udržuje okno otevřené
okno.mainloop()

Related

I want to display data from mongoDB to treeview in Python tkinter

I saw this video: https://www.youtube.com/watch?v=W0l0r0PekvM&t=20s
The code could display data but it display by many Grid together so i can not create a Scrollbar.
you can see the function display data in CRUD() -> creategrid(n)
sorry for my bad English ^^
my code:
from tkinter import *
import tkinter as tk
from tkinter import ttk
import pymongo
from tkinter import messagebox
from tkinter import filedialog
from PIL import Image, ImageTk
import pybase64 as base64
import gridfs
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["enrollmentsystem"] #database file
mycol = mydb["employees"]
mycol2 = mydb["fs.files"]
def CRUD():
lst=[["ID","Name","Age","Departure","Gender","Skill","Working (Y)","Trained (Y)","Salary"]]
window=tk.Toplevel(w1)
window.title("UPDATE PROFILE")
window.geometry('300x400')
window.configure(bg="bisque2")
window3=tk.Toplevel(window)
window3.title("UPDATE PROFILE")
window3.geometry('+%d+%d' % (100,100))
window3.configure(bg="bisque2")
def callback(event):
global lstindex
li=[]
li=event.widget._values
lstindex=li[1]
cid.set(lst[li[1]][0])
cname.set(lst[li[1]][1])
cage.set(lst[li[1]][2])
cdept.set(lst[li[1]][3])
cgender.set(lst[li[1]][4])
cskill.set(lst[li[1]][5])
cwyear.set(lst[li[1]][6])
ctyear.set(lst[li[1]][7])
csalary.set(lst[li[1]][8])
def creategrid(n):
lst.clear()
lst.append(["ID","Name","Age","Departure","Gender","Skill","Working (Y)","Trained (Y)","Salary"])
cursor = mycol.find({})
for text_fromDB in cursor:
empid=str(text_fromDB["empid"])
empname=str(text_fromDB["empname"].encode('utf-8').decode('utf-8'))
empage=str(text_fromDB["empage"].encode('utf-8').decode('utf-8'))
empdept=str(text_fromDB["empdept"].encode('utf-8').decode('utf-8'))
empgender=str(text_fromDB["empgender"].encode('utf-8').decode('utf-8'))
empskill=str(text_fromDB["empskill"].encode('utf-8').decode('utf-8'))
empwyear=int(text_fromDB["empwyear"].encode('utf-8').decode('utf-8'))
emptyear=int(text_fromDB["emptyear"].encode('utf-8').decode('utf-8'))
empsalary=float(text_fromDB["empsalary"].encode('utf-8').decode('utf-8'))
lst.append([empid,empname,empage,empdept,empgender,empskill,empwyear,emptyear,empsalary])
for i in range(len(lst)):
for j in range(len(lst[0])):
mgrid=tk.Entry(window3,width=10)
mgrid.insert(tk.END, lst[i][j])
mgrid._values =mgrid.get(),i
mgrid.grid(row=i+12,column=j+11)
mgrid.bind("<Button-1>",callback)
if n==1:
for label in window.grid_slaves():
if int(label.grid_info()["row"]) >11:
label.grid_forget()
def msgbox(msg,titlebar):
result = messagebox.askokcancel(title=titlebar, message=msg)
return result
def save():
r=msgbox("save record?","record")
if r==True:
newid = mycol.count_documents({})
if newid!=0:
newid = mycol.find_one(sort=[("empid", -1)])["empid"]
id=newid+1
cid.set(id)
mydict = {"empid": int(custid.get()),"empname":custname.get(), "empage":custage.get(),
"empdept":custdept.get(),"empgender":custgender.get(),"empskill":custskill.get(),
"empwyear":custwyear.get(),"emptyear":custtyear.get(),"empsalary":custsalary.get()}
x = mycol.insert_one(mydict)
messagebox.showinfo("info", "save completed, please add photo")
creategrid(1)
creategrid(0)
def delete():
r=msgbox("Delete?", "record")
if r ==True:
myquery = {"empid":int(custid.get())}
mycol.delete_one(myquery)
creategrid(1)
creategrid(0)
def update():
r=msgbox("Update?","record")
if r ==True:
myquery={"empid":int(custid.get())}
newvalues={"$set":{"empname":custname.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empage":custage.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empdept":custdept.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empgender":custgender.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empskill":custskill.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empwyear":custwyear.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"emptyear":custtyear.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empsalary":custsalary.get()}}
mycol.update_one(myquery,newvalues)
creategrid(1)
creategrid(0)
def upload_file(): # Image upload and display
global filename,img, fs
f_types =[('Png files','*.png'),('Gif Files', '*.gif'),('PMG files','*.pmg'),('jpg files','*.jpg')]
filename = filedialog.askopenfilename(filetypes=f_types,defaultextension='.png')
img=Image.open(filename)
img=img.resize((150,150)) # new width & height
img=ImageTk.PhotoImage(img)
e1 =tk.Label(picker)
e1.grid(row=15,column=1)
e1.image = img
e1['image']=img
def saveimage():
global filename
r=msgbox("save image?","image")
if r==True:
# encode image to binary text
with open(filename, "rb") as image:
# read the image as text and convert it to binary
image_string = base64.b64encode(image.read())
# create Gridfs instance
fs = gridfs.GridFS(mydb)
# add the image to database
def alreadyExists():
return bool(mycol2.find_one({'filename' : custid.get()}))
if alreadyExists() == True:
messagebox.showerror("Error", "ID exist")
else:
put_image = fs.put(image_string, filename = custid.get())
picker = tk.Frame(window,width=150, height=150)
picker.place(x=1, y=250)
b2 = tk.Button(window, text='Upload photo',
command = lambda:upload_file()).place(x=180, y=310)
b3 = tk.Button(window, text='Save photo',
command = lambda:saveimage()).place(x=180, y=340)
label =tk.Label(window, text="EMPLOYEE ENLISTMENT FORM", width=25, height=1, bg="cornflower blue",anchor="center")
label.grid(column=2, row=1)
label = tk.Label(window, text="Employee ID:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=2)
cid = tk.StringVar()
custid = tk.Entry(window,width=33, textvariable=cid)
custid.grid(column=2, row=2)
custid.configure(state=tk.DISABLED)
label = tk.Label(window, text="Employee Name:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=3)
cname = tk.StringVar()
custname = tk.Entry(window,width=33, textvariable=cname)
custname.grid(column=2, row=3)
age = []
for i in range(1960,2002):
age.append(i)
label=tk.Label(window, text="Employee BirthYear:", width=20, height=1, bg="cadet blue")
label.grid(row=4,column=1)
cage = tk.IntVar()
custage = ttk.Combobox(window,width=30, values=age)
custage.grid(row=4,column=2)
label=tk.Label(window, text="Employee Departure:", width=20, height=1, bg="cadet blue")
label.grid(row=5,column=1)
cdept = tk.StringVar()
dept=['Sale','Marketing']
custdept = ttk.Combobox(window,width=30, values=dept)
custdept.grid(row=5,column=2)
label=tk.Label(window, text="Employee Gender:", width=20, height=1, bg="cadet blue")
label.grid(row=6,column=1)
gender=['Male','Female']
cgender = tk.StringVar()
custgender = ttk.Combobox(window,width=30, values=gender)
custgender.grid(row=6,column=2)
label=tk.Label(window, text="Employee Skill:", width=20, height=1, bg="cadet blue")
label.grid(row=7,column=1)
cskill = tk.StringVar()
skill=['SQL, C#, Python','SQL, C#, C++','SQL, Python, C++','SQL, C++','SQL, Python','SQL, C#']
custskill = ttk.Combobox(window,width=30, values=skill)
custskill.grid(row=7,column=2)
label = tk.Label(window, text="Employee WorkingYear:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=8)
cwyear = tk.IntVar()
custwyear = tk.Entry(window,width=33, textvariable=cwyear)
custwyear.grid(column=2, row=8)
label = tk.Label(window, text="Employee Trained (Y):", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=9)
ctyear = tk.IntVar()
custtyear = tk.Entry(window,width=33, textvariable=ctyear)
custtyear.grid(column=2, row=9)
label = tk.Label(window, text="Employee Salary:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=10)
csalary = tk.DoubleVar()
custsalary = tk.Entry(window,width=33, textvariable=csalary)
custsalary.grid(column=2, row=10)
creategrid(1) #create textfield grid vi o tren chay tu grid 1
savebtn = tk.Button(window,text="Save", command=save).place(x=180, y=275)
savebtn = tk.Button(window,text="Delete", command=delete).place(x=220, y=275)
savebtn = tk.Button(window,text="Update", command=update).place(x=270, y=275)
btnClose=tk.Button(window, text="Close me", command=window.destroy).place(x=180, y=370)
# Tim kiem anh dua tren ID
def searchImage():
window2=tk.Toplevel(w1)
window2.title("BROWSE")
window2.geometry('+%d+%d' % (100,100))
picker2 = tk.Frame(window2,width=30, height=1)
picker2.grid(row=1, column=3,rowspan = 10)
a = tk.Entry(picker2,width=33)
a.grid(column=2, row=11)
def checkid():
def alreadyExists():
return bool(mycol2.find_one({'filename' : a.get()}))
if alreadyExists() == True:
messagebox.showinfo("info", "ID exist")
fs = gridfs.GridFS(mydb)
data = mycol2.find_one({'filename' : a.get()})
my_id = data['_id']
outputdata =fs.get(my_id).read()
outputdata=outputdata.decode()
outputdata = base64.b64decode((outputdata))
dowloadlocation = "image.jpg"
output = open(dowloadlocation, "wb")
output.write(outputdata)
output.close()
bgetdisplay.config(state='active')
else:
messagebox.showerror("Error", "ID doesn't exist, please retype")
bgetdisplay.config(state='disabled')
def display():
root = Toplevel(window2)
path = "image.jpg"
img = Image.open(path)
img=img.resize((300,300))
img = ImageTk.PhotoImage(img)
panel = tk.Label(root, image=img)
panel.photo = img
panel.grid(column=1,row=1)
bgetdisplay = tk.Button(window2,state ='disabled', text='display image',
width=10,height=2,command = lambda:display())
bgetdisplay.grid(column = 5, row = 2)
bgetid = tk.Button(window2, text='checkID',
width=10,height=2,command = lambda:checkid()).grid(column = 4 ,row = 2)
label = tk.Label(picker2, text="browse photo(input id):", width=20, height=1, bg="cornflower blue")
label.grid(column=1, row=11)
w1=Tk()
btnOpen=tk.Button(w1,text ="Create, update, Delete",width=20,height=4, command=CRUD).place(x=120, y=20)
btnOpen=tk.Button(w1,text ="Search photo",width=20,height=4, command=searchImage).place(x=120, y=100)
w1.geometry('400x200')
w1.title("HUMAN RESOURES")
w1.mainloop()
I want to display data in a treeview to create a scrollbar.
Can anyone help to to change this display code

How to compile python EXE script that can be used on windows computer without python programme

I am struggling ensure python script work on windows computer that does not have python installer. The script below only works on the computer with python software not sure where l am going wrong. Result is if uploaded on another computer no pictures or path is wrong. l am new to python can you please help as l dont know where l am going wrong. Thanks in advance
"""
from tkinter import*
import tkinter as tk
from tkinter import ttk
from datetime import datetime
windo = Tk()
windo.resizable(width=FALSE, height=FALSE)
windo.geometry("600x400")
windo.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
def han():
print("Forms to be completed")
import tkinter as tk
from tkinter import ttk
from datetime import datetime
root = Tk()
root.resizable(width=FALSE, height=FALSE)
root.geometry("680x670")
root.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
fun8 = Label(root, text="Running times comp :")
fun8.place(x=10,y=120)
var32 = IntVar()
chekbtn_1 = Checkbutton(root ,text="Yes", variable=var32)
chekbtn_1.place(x=180,y=120)
var33 = IntVar()
chekbtn_2 = Checkbutton(root ,text="No", variable=var33)
chekbtn_2.place(x=230,y=120)
def cli(value):
print("Severity of aggression")
print(value)
def clic(value):
print("Area of aggression")
print(value)
def click(value):
print("Nature of aggression")
print(value)
def save_funct():
print("Saved")
frame = LabelFrame(root, padx=5, pady=5)
v = tk.StringVar()
v.set("None")
lab2 = Label(frame, text="Select Level of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame, variable=v,value="1-No Concern", text="1-No Concern", command=lambda:cli(v.get()))
radioButton2 = Radiobutton(frame, variable=v, value="2-Not Severe",text="2-Not Severe",command=lambda:cli(v.get()) )
radioButton3 = Radiobutton(frame, variable=v, value="3-Slightly Severe",text="3-Slightly Severe",command=lambda:cli(v.get()) )
radioButton4 = Radiobutton(frame, variable=v, value="6-Extremely Severe",text="6-Extremely Severe",command=lambda:cli(v.get()) )
radioButton5 = Radiobutton(frame, variable=v,value="5-Severe", text="5-Severe", command=lambda:cli(v.get()))
radioButton6 = Radiobutton(frame, variable=v,value="4-Fairly Severe", text="6-Fairly Severe", command=lambda:cli(v.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame.place(x=35, y=155)
frame1 = LabelFrame(root, padx=5, pady=5)
vv = tk.StringVar()
vv.set("None")
lab2 = Label(frame1, text="Areas of Aggressions", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame1, variable=vv,value="Lounge", text="Lounge", command=lambda:clic(vv.get()))
radioButton2 = Radiobutton(frame1, variable=vv, value="Kitchen",text="Kitchen",command=lambda:clic(vv.get()) )
radioButton3 = Radiobutton(frame1, variable=vv, value="Bedroom 1",text="Bedroom 1",command=lambda:clic(vv.get()) )
radioButton4 = Radiobutton(frame1, variable=vv, value="Bedroom 2",text="Bedroom 2",command=lambda:clic(vv.get()) )
radioButton5 = Radiobutton(frame1, variable=vv,value="Bedroom 3", text="Bedroom 3", command=lambda:clic(vv.get()))
radioButton6 = Radiobutton(frame1, variable=vv,value="Dinning ", text="Dinning", command=lambda:clic(vv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame1.place(x=35, y=255)
frame2 = LabelFrame(root, padx=5, pady=5)
vvv = tk.StringVar()
vvv.set("None")
lab2 = Label(frame2, text="Nature of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame2, variable=vvv,value="Punching", text="Punching", command=lambda:click(vvv.get()))
radioButton2 = Radiobutton(frame2, variable=vvv, value="Kicking",text="Kicking",command=lambda:click(vvv.get()) )
radioButton3 = Radiobutton(frame2, variable=vvv, value="Pushing ",text="Pushing",command=lambda:click(vvv.get()) )
radioButton4 = Radiobutton(frame2, variable=vvv, value="Forceful",text="Forceful",command=lambda:click(vvv.get()) )
radioButton5 = Radiobutton(frame2, variable=vvv,value="Punching Walls", text="Punching Walls", command=lambda:click(vvv.get()))
radioButton6 = Radiobutton(frame2, variable=vvv,value="Clinch fists ", text="Clinch fists", command=lambda:click(vvv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame2.place(x=35, y=355)
buttnn = Button(root, text="Save", width=10, height=2, fg= "blue",command=save_funct)
buttnn.place(x=570, y=615)
root.mainloop()
def st_ii():
print("Redirected")
canvas=Canvas(width=400,height=200, bg="blue")
canvas.place(x=200,y=130)
photo=PhotoImage(file="C:\\Users\\breada\\OneDrive\\Desktop\\Forest.png")
canvas.create_image(0,0,image=photo, anchor=NW)
toolbar = Frame(windo, bg="powder blue", padx=3, pady=20)
insertButt= Button(toolbar,text = "A-Form",command =han)
insertButt.pack(side=LEFT, padx=6,pady=2)
shift_planButt = Button(toolbar, text= "B-Form",command =st_ii)
shift_planButt.pack(side=LEFT, padx=6,pady=2)
toolbar.pack(side=TOP,fill=X)
windo.mainloop()
"""
If you compile your script into an executable file, for example by using "auto-py-to-exe", then the resulting .exe-file can be run on any computer with the same architecture as the one you created the .exe file on.
You can include other files or folders containing pictures or icons using a simple GUI.
you can install it with pip:
$ pip install auto-py-to-exe
or directly from github:
https://github.com/brentvollebregt/auto-py-to-exe

How to add Checkbox to every row of table to update/delete the row data from phpmyadmin in tkinter

May i know where and how do i need to do. I want to add a checkbox in every row and when it checked, the button of update or delete will only effect to the checked row.
I am new in python and currently i'm doing this for my project gui, is that anyone can help or if any suggestion you're welcome. Thanks
Below is my code:
from tkinter import *
from tkinter import messagebox
import mysql.connector
win = Tk()
win.title("Admin Signup")
win.geometry("750x400+300+90")
frame1 = Frame(win)
frame1.pack(side = TOP, fill=X)
frame2 = Frame(win)
frame2.pack(side = TOP, fill=X)
frame3 = Frame(win)
frame3.pack(side = TOP, padx = 10, pady=15)
frame4 = Frame(win)
frame4.pack(side = TOP, padx = 10)
frame5 = Frame(win)
frame5.pack(side = LEFT, padx = 10)
lbl_title = Label(frame1, text = "User List", font = ("BOLD 20"))
lbl_title.pack(side = TOP, anchor = "w", padx = 20, pady = 20)
btn_register = Button(frame2, text = "Register User")
btn_register.pack(side = TOP, anchor = "e", padx=20)
lbl01 = Label(frame3, text="Username", width=17, anchor="w", relief="raised")
lbl01.grid(row=0, column=0)
lbl02 = Label(frame3, text="Password", width=17, anchor="w", relief="raised")
lbl02.grid(row=0, column=1)
lbl03 = Label(frame3, text="Full Name", width=17, anchor="w", relief="raised")
lbl03.grid(row=0, column=2)
lbl04 = Label(frame3, text="Ic Number", width=17, anchor="w", relief="raised")
lbl04.grid(row=0, column=3)
lbl05 = Label(frame3, text="Staff Id", width=17, anchor="w", relief="raised")
lbl05.grid(row=0, column=4)
mydb = mysql.connector.connect(
host = "localhost",
user = "username",
password = "password",
database = "adminacc"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM acc")
i = 0
for details in mycursor:
for j in range(len(details)):
e = Entry(frame4, width=17, relief=SUNKEN)
e.grid(row=i, column=j)
e.insert(END, details[j])
e.config(state=DISABLED, disabledforeground="blue")
i = i+1
btn_update = Button(frame5, text = "Update")
btn_update.grid(row=0, column=0, padx=15)
btn_delete = Button(frame5, text = "Delete")
btn_delete.grid(row=0, column=1)
win.mainloop()
Since every row behaves the same, suggest to use a class to encapsulate the behavior:
class AccountInfo:
def __init__(self, parent, details, row):
self.entries = []
# create entry box for each item in 'details'
for col, item in enumerate(details):
e = Entry(parent, width=17, relief=SUNKEN, disabledforeground='blue', bd=2)
e.grid(row=row, column=col)
e.insert(END, item)
e.config(state=DISABLED)
self.entries.append(e)
# create the checkbutton to select/deselect current row
self.var = BooleanVar()
Checkbutton(parent, variable=self.var, command=self.state_changed).grid(row=row, column=col+1)
def state_changed(self):
state = NORMAL if self.selected else DISABLED
# enable/disable entries except username
for e in self.entries[1:]:
e.config(state=state)
#property
def selected(self):
return self.var.get()
#property
def values(self):
return tuple(x.get() for x in self.entries)
Then using the class to create the required rows for each record retrieved from database:
mycursor.execute("SELECT * FROM acc")
accounts = [] # used to store the rows (accounts)
for row, details in enumerate(mycursor):
acc = AccountInfo(frame4, details, row)
accounts.append(acc)
The saved accounts can then be used in the callbacks of Update and Delete buttons:
def update_accounts():
for acc in accounts:
if acc.selected:
print(acc.values)
# do whatever you want on this selected account
btn_update = Button(frame5, text="Update", command=update_accounts)
Same logic on Delete button.
Note that you can modify the AccountInfo class to add functionalities that suit what you need.

Need to validate the input of the name weight and height entries

https://github.com/Rodneyst/lv100roxas-gmail.com/blob/master/finalproject
Can look over the full code here. The link goes to the full code, I pull all the answer with one button using stringvar. Please answer I have 2 days left and haven't had any luck.
# Username widget
self.prompt_label5 = tkinter.Label(self.top_frame,
text='Enter your Name:' ,bg="red", fg="yellow", font="none 12 bold")
self.name_entry = tkinter.Entry(self.top_frame,
width=10)
# weight widget
self.prompt_label1 = tkinter.Label(self.top_frame,
text='Enter your weight(lbs):' ,bg="red", fg="yellow", font="none 12 bold")
self.weight_entry = tkinter.Entry(self.top_frame,
width=10)
def getworkout(self):
weight = float(self.weight_entry.get())
height = float(self.height_entry.get())
How would I validate these user inputs? Please help — I cannot figure it out. I want to get a pop-up window to show when the user inputs an integer for name and when they enter a string for weight and height, ValueErrors. Please help!
Code is messy, so make it look better :) But I think it does, what you asked about. I edited it in a hurry. Name also accept more signs then just letters (excluding integers) - it's easy to validate if necessery.
import tkinter
from tkinter import ttk
from tkinter import messagebox
import random
# GUI
class WorkoutGUI:
def __init__(self):
# Main window
self.main_window = tkinter.Tk()
self.main_window.title("Workout Generator")
self.main_window.geometry('1200x600')
# Frames
self.top_frame = tkinter.Frame()
self.mid_frame = tkinter.Frame()
self.bottom_frame = tkinter.Frame()
validation1 = self.top_frame.register(entry_validation_1)
validation2 = self.top_frame.register(entry_validation_2)
# TOP FRAME
# username widget
self.prompt_label1 = tkinter.Label(self.top_frame,
text='Enter your Name:', bg="red", fg="yellow", font="none 12 bold")
self.name_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation1, '%S'))
# weight widget
self.prompt_label2 = tkinter.Label(self.top_frame,
text='Enter your weight(lbs):', bg="red", fg="yellow", font="none 12 bold")
self.weight_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation2, '%S'))
# height widget
self.prompt_label3 = tkinter.Label(self.top_frame,
text='Enter your height(in):', bg="red", fg="yellow",
font="none 12 bold")
self.height_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation2, '%S'))
# gender widget
self.prompt_label4 = tkinter.Label(self.top_frame,
text='Select your gender:', bg="red", fg="yellow",
font="none 12 bold")
self.gender_entry = tkinter.IntVar()
self.gender_entry.set(1)
# radio buttons for gender choice
self.rb1 = tkinter.Radiobutton(self.top_frame,
text='Male',
variable=self.gender_entry,
value=1)
self.rb2 = tkinter.Radiobutton(self.top_frame,
text='Female',
variable=self.gender_entry,
value=2)
# goal widget
self.prompt_label5 = tkinter.Label(self.top_frame,
text='Select your goal:', bg="red", fg="yellow",
font="none 12 bold")
self.goal_entry = tkinter.IntVar()
self.goal_entry.set(1)
# radio buttons for goal choice
self.rb3 = tkinter.Radiobutton(self.top_frame,
text='Lose Weight',
variable=self.goal_entry,
value=1)
self.rb4 = tkinter.Radiobutton(self.top_frame,
text='Maintain',
variable=self.goal_entry,
value=2)
self.rb5 = tkinter.Radiobutton(self.top_frame,
text='Build Muscle Mass',
variable=self.goal_entry,
value=3)
# packing widgets
self.prompt_label1.pack(side='top')
self.name_entry.pack(side='top')
self.prompt_label2.pack(side='top')
self.weight_entry.pack(side='top')
self.prompt_label3.pack(side='top')
self.height_entry.pack(side='top')
self.prompt_label4.pack(side='top')
self.rb1.pack(side='top')
self.rb2.pack(side='top')
self.prompt_label5.pack(side='left')
self.rb3.pack(side='left')
self.rb4.pack(side='left')
self.rb5.pack(side='left')
# MIDDLE FRAME
self.descr_label = tkinter.Label(self.mid_frame,
text='Workout for you:')
self.value = tkinter.StringVar()
self.workout_label = tkinter.Label(self.mid_frame,
textvariable=self.value,
width=250, height=20, bg="white")
# packing widgets
self.descr_label.pack(side='top')
self.workout_label.pack(side='bottom')
# BOTTOM FRAME
# buttons
self.display_button = tkinter.Button(self.bottom_frame,
text='Get Workout!',
command=self.getworkout)
self.quit_button = tkinter.Button(self.bottom_frame,
text='Quit',
command=self.main_window.destroy)
# pack the buttons
self.display_button.pack(side='left')
self.quit_button.pack(side='right')
# packing frames
self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()
# fucnction to get outputs
def getworkout(self):
# Gather User information
name = str(self.name_entry.get())
gymSerial = random.randint(0, 10000)
weight = float(self.weight_entry.get())
height = float(self.height_entry.get())
gender = (self.gender_entry.get())
goal = (self.goal_entry.get())
def entry_validation_1(x):
if x.isdecimal():
messagebox.showwarning("Wrong input!", "Name must be a string - not integer.")
return False
else:
return True
def entry_validation_2(y):
if y.isdecimal():
return True
else:
messagebox.showwarning("Wrong input!", "Weight and height must be a numerical value - not string")
return False
def main():
root = tkinter.Tk()
ex = WorkoutGUI()
root.mainloop()
if __name__ == '__main__':
main()
Link is not working, but I wrote my own code as an example. I think it's very close to what you need.
The method is called entry validation and you can find some more info here:
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/entry-validation.html
Feel free to ask if you have any concerns :)
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
# tkinter main window
root = tk.Tk()
root.title('Validation')
root.geometry('300x300')
def entry_validation_1(x):
if x.isdecimal():
messagebox.showwarning("Wrong input!", "Name must be a string - not integer.")
return False
else:
return True
def entry_validation_2(y):
if y.isdecimal():
return True
else:
messagebox.showwarning("Wrong input!", "Weight and height must be a numerical value - not string")
return False
validation1 = root.register(entry_validation_1)
validation2 = root.register(entry_validation_2)
name = tk.Entry(root, width='9', justify='center', validate='key', validatecommand=(validation1, '%S'))
weight_or_height = tk.Entry(root, width='9', justify='center', validate='key', validatecommand=(validation2, '%S'))
label_name = tk.Label(root, text='name - INTEGER NOT ACCEPTED')
label_weight_or_height = tk.Label(root, text='weight or height - STRING NOT ACCEPTED')
name.grid(row=0, column=0, padx=0, pady=0)
label_name.grid(row=0, column=1, padx=0, pady=0)
weight_or_height.grid(row=1, column=0, padx=0, pady=0)
label_weight_or_height.grid(row=1, column=1, padx=0, pady=0)
tk.mainloop()

python tkinter and scope of stringvar()

Python noob here. I've created a simple tkinter app with 6 frames. Using multiple frames was the easiest way I could find to get all of the widgets to line up.
I want to have a text entry field in one of the frames that can be updated by other functions in the code. However, no matter what I try, I cannot get blah.set( "blah" ) to work.
I'm not using the self/parent stuff because I have not been able to figure that out yet. Here's what I've got:
def Next () :
glob_current_company_display.set( "test" )
def makeWindow () :
win = Tk()
win.title('Finder')
win.geometry('+842+721')
# ************************************************************************
# Frame 2
frame2 = Frame(win)
button_03 = Button(frame2, text="Next", width=10, command=Next)
button_03.pack(side=LEFT)
# ************************************************************************
# Frame 5
frame5 = Frame(win)
co_name_label = Label(frame5, text="Company Name: ", justify=LEFT)
co_name_label.pack(side=LEFT)
global glob_current_company_display
glob_current_company_display = StringVar()
co_name_entry = Entry(frame5, width=50, textvariable=glob_current_company_display)
co_name_entry.pack(side=LEFT)
# ************************************************************************
# Pack the frames
frame5.pack(side=TOP, pady=5, padx=5)
frame2.pack(side=TOP, pady=5, padx=5)
return win
win = makeWindow()
win.mainloop()
You probably should investigate the "self/parent stuff". It's comes in very handy for this kind of stuff. For now: you could put the creation of the global variable before the button_03 that has Next() as command (which has a reference to te global in it).
from Tkinter import *
def Next () :
glob_current_company_display.set( "test" )
def makeWindow () :
win = Tk()
win.title('Finder')
win.geometry('+842+721')
global glob_current_company_display
glob_current_company_display = StringVar()
# ************************************************************************
# Frame 2
frame2 = Frame(win)
button_03 = Button(frame2, text="Next", width=10, command=Next)
button_03.pack(side=LEFT)
# ************************************************************************
# Frame 5
frame5 = Frame(win)
co_name_label = Label(frame5, text="Company Name: ", justify=LEFT)
co_name_label.pack(side=LEFT)
co_name_entry = Entry(frame5, width=50, textvariable=glob_current_company_display)
co_name_entry.pack(side=LEFT)
# ************************************************************************
# Pack the frames
frame5.pack(side=TOP, pady=5, padx=5)
frame2.pack(side=TOP, pady=5, padx=5)
return win
win = makeWindow()
win.mainloop()

Categories

Resources