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

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

Related

PRNG, python. 1 button - 2 function?

help me please. It is necessary that when the 'Generate' button(gen) is pressed, 2 functions (clicked1, gen1) are executed. But it only run clicked1.
I read that I can use lambda; or create a separate function that includes the ones you need. But gen1 still fails.
but the most important thing is that
when I removed clicked1 from the code completely, then gen1 didn't work either(
import tkinter
from tkinter import *
from tkinter import messagebox, scrolledtext
from tkinter.ttk import Progressbar
from tkinter import ttk
from PIL import Image, ImageTk
from random import randint
class App:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Генератор")
self.window['bg'] = '#FFF5EE'
self.window.geometry('660x550')
self.window.resizable(False,False)
self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))
self.lb1.grid(column=0, row=2)
self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb2.grid(column=1, row=3)
self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb3.grid(column=1, row=4)
self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb4.grid(column=4, row=3)
self.txt2 = Entry(self.window,width=10, borderwidth=3)
self.txt2.grid(column=2, row=3)
self.txt3 = Entry(self.window,width=10, borderwidth=3)
self.txt3.grid(column=2, row=4)
self.txt4 = Entry(self.window,width=10, borderwidth=3)
self.txt4.grid(column=5, row=3)
self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.gen = Button(self.window, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
self.gen.grid(row=4, column=6)
self.canvas = tkinter.Canvas(self.window, height=250, width=230)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)
self.btn = Button(self.window, text="Delete", command=self.delete)
self.btn.grid(column=6, row=5)
self.exit = Button(self.window, text="Exit", command=quit)
self.exit.grid(column=6, row=6)
self.window.mainloop()
def clicked1(self):
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror("Error", "Please enter correct numbers!")
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
else:
messagebox.showerror("Error", "Please enter correct numbers!")
def delete(self):
self.scrolltxt.delete(1.0, END)
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
app= App()
I don't understand what I'm doing wrong
I hope I explained the problem clearly
Both the clicked1() and gen1() are executed when the Generate button is clicked. However nothing will be inserted into the text box because the text box is disabled.
You need to enable the text box before inserting text and disabled it back after:
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete("1.0", END) # better use "1.0" instead of 1.0
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box

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

RE: TKinter Table Row Deletion (PYTHON)

(If anyone has seen my previous question, I found a way to save the row indexes and use them in the delete function :3)
Is there a way to stop/delete a running function/table on a button click? I am making a simple customer registration program which saves data from text fields (cID, custName, custEmail, and custBday) and deletes a selected row. My problem is that whenever I delete a row, the last row somehow leaves/lags behind creating this duplicate whenever a row is deleted. Any suggestions or is there something I've done wrong or I've missed?
My Code:
from tkinter import *
from tkinter import messagebox
import tkinter as tk
at = False
dotcom = False
list = [['ID', 'NAME', 'EMAIL', 'BIRTHDATE']]
recentIndex = []
ID = 1
storedIndex = 0
def callback(event):
custid.config(state=NORMAL)
custid.delete('1.0', END)
custid.insert(1.0, list[event.widget._values][0])
custid.config(state=DISABLED)
cName.set(list[event.widget._values][1])
cEmail.set(list[event.widget._values][2])
birthdate.set(list[event.widget._values][3])
indexPosition = event.widget._values
recentIndex.append(indexPosition)
print(recentIndex)
def createTable():
for i in range(len(list)):
for j in range(len(list[0])):
mgrid = tk.Entry(window, width = 10, bg= 'yellow')
mgrid.insert(tk.END, list[i][j])
mgrid._values= i
mgrid.grid (row = i + 5,column = j + 5)
mgrid.bind("<Button-1>", callback)
def delete():
try:
list.pop(recentIndex[-1])
if recentIndex[-1] > 0 or NONE:
msgbox("Data Delete", "Record")
createTable()
else:
msgbox("No Data Selected", "record")
return
except:
msgbox("No Data Selected", "record")
def save ():
custid.config(state= NORMAL)
initialValue = int(custid.get('1.0', END))
custid.delete('1.0', END)
list.append([ID, custName.get(), custEmail.get(), custBday.get()])
custid.insert(1.0, initialValue + 1)
custid.config(state=DISABLED)
createTable()
msgbox("Saved", "Record")
ID = ID + 1
def msgbox (msg, titlebar):
messagebox.showinfo(title = titlebar, message=msg)
def products():
window = Tk()
window.title("Products Form")
window.geometry("550x400")
window.configure(bg="orange")
window = Tk()
window.title("Sample Window")
window.geometry("550x400")
window.configure(bg="orange")
menubar = Menu(window)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Products", command=products)
filemenu.add_command(label="Orders")
filemenu.add_separator()
filemenu.add_command(label="Close", command = window.quit)
window.config(menu=menubar)
labelTitle = Label(window, text="Customer Registration System", width=30, height=1, bg="yellow", anchor= "center")
labelTitle.config(font=("Courier", 10))
labelTitle.grid(column=2, row=1)
labelID = Label(window, text="Customer ID", width = 20, height = 1, bg = "yellow")
labelID.grid(column=1, row=2)
cID = StringVar()
custid = Text(window, width=15, height=1)
custid.grid(column=2, row=2)
custid.insert(1.0, "1")
custid.config(state = DISABLED)
labelNameCheck = Label(window, text="Last Name, First Name", width = 20, height = 1, bg = "yellow")
labelNameCheck.grid(column=3, row=3)
labelName = Label(window, text="Customer Name", width = 20, height = 1, bg = "yellow")
labelName.grid(column=1, row=3)
cName = StringVar()
custName = Entry(window, textvariable = cName)
custName.grid(column=2, row=3)
labelEmail = Label(window, text="Customer Email", width = 20, height = 1, bg = "yellow")
labelEmail.grid(column=1, row=4)
cEmail = StringVar()
custEmail = Entry(window, textvariable = cEmail)
custEmail.grid(column=2, row=4)
custEmail.bind("<KeyRelease>", keyup)
labelEmail = Label(window, text="[a-z]#[a-z].com", width = 20, height = 1, bg = "yellow")
labelEmail.grid(column=3, row=4)
labelBday = Label(window, text="Customer Birthdate", width = 20, height = 1, bg = "yellow")
labelBday.grid(column=1, row=5)
birthdate= StringVar()
custBday = Entry(window, textvariable = birthdate)
custBday.grid(column=2, row=5)
custBday.bind("<KeyRelease>", keyupBdate)
birthdateCheck = Label(window, text="mm/dd/yyyy", width = 20, height = 1, bg = "yellow")
birthdateCheck.grid(column=3, row=5)
savebtn = Button(text = "Save", command = save)
savebtn.grid(column=1)
deletebtn = Button(text = "Delete", command = delete)
deletebtn.grid(column=1)
window.mainloop()
You need to delete current displayed records before showing updated records inside createTable(). Also better create a frame for showing the records, so that it is more easier to clear the displayed records:
def createTable():
# clear current displayed records
for w in tableFrame.winfo_children():
w.destroy()
# populate records
for i in range(len(list)):
for j in range(len(list[0])):
mgrid = tk.Entry(tableFrame, width = 10, bg= 'yellow') # use tableFrame as parent
mgrid.insert(tk.END, list[i][j])
mgrid._values= i
mgrid.grid (row = i,column = j)
mgrid.bind("<Button-1>", callback)
...
# frame for showing records
tableFrame = Frame(window)
tableFrame.grid(row=5, column=5)
...

Why is the thread not working the second time?

I am an amateur in python and I am creating this downloader app using tkinter and urllib.request and I have built the program without any threads and when I downloaded a file it would freeze until the file was downloaded and I didn't want that so I tried threading and events and it seems like it is working perfectly fine but when I want to download a second file it is not working. Why does this happen? What have I done wrong? My code:
from tkinter import *
from tkinter import font as tkFont
import random
import urllib.request
import requests
import threading
import wget
import queue
def printsth():
print("Yay it works! ")
def main_menu():
root = Tk()
root.title('8-bit downloader ')
root.iconbitmap(r"C:\Users\rayanravesh\PycharmProjects\GUI_Calculator\icon.ico")
root.geometry("600x300")
# the top menu
global num, chum, var
num = IntVar()
chum = IntVar()
var = IntVar()
menu = Menu(root)
root.config(menu=menu)
submenu = Menu(menu)
menu.add_cascade(label="Settings", menu=submenu)
def custom_op():
custom = Toplevel()
custom.iconbitmap(r"C:\Users\rayanravesh\PycharmProjects\GUI_Calculator\icon.ico")
submenu.add_command(label="Customization ", command=custom_op)
def settings_op():
global gps
set_win = Toplevel()
set_win.iconbitmap(r"C:\Users\rayanravesh\PycharmProjects\GUI_Calculator\icon.ico")
path_label = Label(set_win, text="Current default download path: ")
path_entry = Entry(set_win, width=30)
file_read = open('Data.txt', 'r')
data_base = file_read.read()
path_entry.insert(0, data_base)
file_read.close()
def default_output():
global location
file_read2 = open('Data.txt', 'r+')
file_read2.truncate(0)
file_read2.close()
write_file2 = open('Data.txt', 'w')
write_file2.write(path_entry.get())
write_file2.close()
location = path_entry.get() + "\\"
default_location = location.replace("\\", "\\\\")
path_btn = Button(set_win, text="Submit ", command=default_output)
path_label.pack(anchor=CENTER, expand=1)
path_entry.pack(anchor=CENTER, expand=1)
path_btn.pack(anchor=CENTER, expand=1)
submenu.add_command(label="Settings ", command=settings_op)
submenu.add_separator()
submenu.add_command(label="Exit", command=root.destroy)
# the section menu
editmenu = Menu(menu)
menu.add_cascade(label="Sections(soon)", menu=editmenu)
editmenu.add_command(label="Downloader", command=printsth)
editmenu.add_command(label="Converter", command=printsth)
editmenu.add_command(label="Media Player", command=printsth)
editmenu.add_command(label="Editor", command=printsth)
# the tool bar
toolbar = Frame(root, bg="light gray")
insert_button = Button(toolbar, text="Insert an image", command=printsth)
insert_button.pack(side=LEFT, padx=2, pady=2)
print_button = Button(toolbar, text="Print", command=printsth)
print_button.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
# the download initiation
def initiate():
event.set()
# the status bar
status_bar = Label(root, text="Downloading...", bd=1, relief=SUNKEN, anchor=W)
status_bar.pack(side=BOTTOM, fill=X)
# the download frame
body_frame = Frame(root, bg="light blue")
download_button = Button(body_frame, text="Download! ", command=initiate, border=3, width=20, height=5)
download_design = tkFont.Font(size=12, slant='italic')
download_button['font'] = download_design
download_button.pack(side=LEFT, pady=5, padx=5)
body_frame.pack(side=LEFT, fill=Y)
# the main interaction menu
inter_frame = Frame(root)
global name_entry, format_entry, url_entry, output_entry
url_entry = Entry(inter_frame, width=30)
label = Label(inter_frame, text="Enter the image URL: ")
file_format = Label(inter_frame, text="Choose your file format: ")
format_entry = Entry(inter_frame, width=30)
file_name = Label(inter_frame, text="File's name: ")
name_entry = Entry(inter_frame, width=30)
check_name = Checkbutton(inter_frame, text="Give a random name", variable=num)
check_format = Checkbutton(inter_frame, text="Download with default format", variable=var)
check_default = Checkbutton(inter_frame, text="Download to default path", variable=chum)
check_default.deselect()
output_path = Label(inter_frame, text="Choose output path: ")
output_entry = Entry(inter_frame, width=30)
file_name.pack(anchor=CENTER, expand=1)
name_entry.pack(anchor=CENTER, expand=1)
check_name.pack(anchor=CENTER, expand=1)
label.pack(anchor=CENTER, expand=1)
url_entry.pack(anchor=CENTER, expand=1)
file_format.pack(anchor=CENTER, expand=1)
format_entry.pack(anchor=CENTER, expand=1)
format_entry.insert(0, '.')
check_format.pack(anchor=CENTER)
output_path.pack(anchor=CENTER, expand=1)
output_entry.pack(anchor=CENTER, expand=1)
check_default.pack(anchor=CENTER, expand=1)
inter_frame.pack(expand=1)
root.mainloop()
# the end!
def download_image():
event.wait()
while event.is_set():
print('hi')
global formatname
if num.get() == 1:
name = random.randrange(1, 1000000)
else:
name = str(name_entry.get())
formatname = str(format_entry.get())
'''if var.get() == 1:
operator = str(url_entry.get())
formatname = '.' + operator[-3] + operator[-2] + operator[-1]
else:
pass'''
fullname = str(name) + formatname
url = str(url_entry.get())
fw = open('file-size.txt', 'w')
file_size = int(requests.head(url, headers={'accept-encoding': ''}).headers['Content-Length'])
fw.write(str(file_size))
fw.close()
path = str(output_entry.get()) + "\\"
if chum.get() == 1:
filee = open('Data.txt', 'r')
destination = filee.read()
path = destination + "\\"
output_entry.insert(0, destination)
filee.close()
else:
output_entry.delete(0, END)
urllib.request.urlretrieve(url, path.replace("\\", "\\\\") + fullname)
event = threading.Event()
t1 = threading.Thread(target=main_menu)
t2 = threading.Thread(target=download_image)
t1.start()
t2.start()
an amateur here as well. But I suspect without knowing anything else about threading, that you can't use event.set() twice in a row.
I guess that at the end of your download_image() function you should call:
event.clear()
See the documentation here.
It might not be the right function, but closing or releasing the thread seems logical to me before you want to call it again. Sorry if it doesn't work.

Placement of tkinter Frame python

I am trying to build a python application and got a little stuck with the placement of the tkinter Frames. I have three frames; one for news, one for calendar and one for Quotes. The placement of news and calendar Frames is okay but i cant get the Quotes Frame to be placed under them, justified to the center. Please help me out with this placement because i cant figure it out myself. Any help is appreciated.
Posted below is the code: -
from tkinter import *
import time
import datetime
from PIL import Image, ImageTk
import requests
import calendar
from apiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import pickle
import googlefonts_installer
from bs4 import BeautifulSoup
class News(Frame):
def __init__(self, parent):
super(News, self).__init__(bg='black')
#url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=caa7f97ce8f2400a9785cbe704afc345"
#json = requests.get(url).json()
self.title = 'Headlines'
self.title_lb = Label(self, text=self.title, font='times 20',bg='black', fg='white')
self.title_lb.pack(side=TOP, anchor=W, pady=15)
#im = Image.open('Newspaper_reduced.png')
#self.pho = ImageTk.PhotoImage(im)
#news1 = json['articles'][0]['title']
#news2 = json['articles'][1]['title']
#news3 = json['articles'][2]['title']
#news4 = json['articles'][3]['title']
#news5 = json['articles'][4]['title']
self.img = Label(self,bg='black')
self.img.pack(anchor=W)
news = ''
self.headline1_lb = Label(self, font = 'times 12' ,bg='black', fg='white')
self.headline1_lb.pack(anchor=W)
self.img2 = Label(self,bg='black')
self.img2.pack(anchor=W)
news2 = ''
self.headline2_lb = Label(self, font='times 12',bg='black', fg='white')
self.headline2_lb.pack(anchor=W)
self.img3 = Label(self,bg='black')
self.img3.pack(anchor=W)
news3 = ''
self.headline3_lb = Label(self, font='times 12',bg='black', fg='white')
self.headline3_lb.pack(anchor=W)
self.img4 = Label(self,bg='black')
self.img4.pack(anchor=W)
news4 = ''
self.headline4_lb = Label(self, font='times 12',bg='black', fg='white')
self.headline4_lb.pack(anchor=W)
self.img5 = Label(self,bg='black')
#self.img5.pack(anchor=W)
news5 = ''
self.headline5_lb = Label(self, font="times 12", bg='black', fg='white')
#self.headline5_lb.pack(anchor=W)
self.show_news()
def show_news(self):
url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=caa7f97ce8f2400a9785cbe704afc345"
json = requests.get(url).json()
im = Image.open('Newspaper_reduced.png')
self.pho = ImageTk.PhotoImage(im)
self.img.configure(image=self.pho)
self.news1 = json['articles'][0]['title']
self.headline1_lb.configure(text=self.news1)
self.img2.configure(image=self.pho)
self.news2 = json['articles'][1]['title']
self.headline2_lb.configure(text=self.news2)
self.img3.configure(image=self.pho)
self.news3 = json['articles'][2]['title']
self.headline3_lb.configure(text=self.news3)
self.img4.configure(image=self.pho)
self.news4 = json['articles'][3]['title']
self.headline4_lb.configure(text=self.news4)
self.img5.configure(image=self.pho)
self.news5 = json['articles'][4]['title']
self.headline5_lb.configure(text=self.news5)
self.after(600000,self.show_news)
class Calendar(Frame):
def __init__(self, parent):
super(Calendar, self).__init__(bg='black')
'''eventTitle = Label(self, text="To do List", font="Courier 25", bg='black', fg='white')
eventTitle.pack()
eventline = '______________________'
event1 = ''
self.event1_lb = Label(self, font='courier 12',bg='black', fg='white')
self.event1_lb.pack()
self.eventline1_lb = Label(self, text = eventline, bg='black',fg='white')
self.eventline1_lb.pack()
event234 = ''
self.event2_lb = Label(self, font='courier 12', bg='black', fg='white')
self.event2_lb.pack()
self.eventline2_lb = Label(self, text = eventline, bg='black',fg='white')
self.eventline2_lb.pack()'''
self.calendars()
#self.reminders()
def calendars(self):
cal = calendar.month(2019,10)
self.calendarlb = Label(self, text=cal, font="Courier 12", justify="left",bg='black', fg='white')
self.calendarlb.pack(side=TOP, anchor=N, fill=BOTH, expand=YES)
def reminders(self):
scopes = ['https://www.googleapis.com/auth/calendar']
#flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", scopes=scopes)
#credentials = flow.run_console()
#pickle.dump(credentials, open("token.pkl", "wb"))
credentials = pickle.load(open("token.pkl", "rb"))
service = build("calendar", "v3" , credentials=credentials)
result = service.calendarList().list().execute()
calendar_id = result['items'][1]['id']
now = datetime.datetime.utcnow()
today = now.isoformat()+'Z'
tomorrow = (now+datetime.timedelta(days=1)).isoformat()+'Z'
outcomes = service.events().list(calendarId=calendar_id, timeMin=today,timeMax=tomorrow,singleEvents=True ,orderBy='startTime').execute()
self.eventa = outcomes['items'][0]['summary']
self.eventb = outcomes['items'][0]['end']['dateTime']
self.event1 = str(self.eventa + '\n' + self.eventb)
self.event1_lb.configure(text=self.event1)
self.event2 = outcomes['items'][1]['summary']
self.event23 = outcomes['items'][1]['end']['dateTime']
self.event234 = str(self.event2 + '\n' + self.event23)
self.event2_lb.configure(text=self.event234)
'''eventline = '______________________'
eventTitle = Label(self, text="To do List", font="Courier 25", bg='black', fg='white')
eventTitle.pack()
event1_lb = Label(self, text= event123, font='courier 12',bg='black', fg='white')
event1_lb.pack()
#event12_lb = Label(self, text=event12, font='courier 12', bg='black',fg='white')
#event12_lb.pack()
eventline1_lb = Label(self, text = eventline, bg='black',fg='white')
eventline1_lb.pack()
event2_lb = Label(self, text=event2, font='courier 12', bg='black', fg='white')
event2_lb.pack()
event22_lb = Label(self, text=event22, font='courier 12',bg='black', fg='white')
event22_lb.pack()
eventline2_lb = Label(self, text = eventline, bg='black',fg='white')
eventline2_lb.pack()'''
self.after(1000,self.reminders)
class Quotes(Frame):
def __init__(self,parent):
super(Quotes,self).__init__(bg='black')
req = requests.get('https://www.brainyquote.com/quote_of_the_day')
soup = BeautifulSoup(req.text,'lxml')
imageQuote = soup.find('img')
#print(imageQuote['alt'])
text_lb = Label(self,text=imageQuote['alt'],font=("Courier 12"),bg='black',fg='white')
text_lb.pack(side=RIGHT)
class FullscreenWindow:
def __init__(self):
self.tk = Tk()
self.tk.configure(bg='black')
self.tk.title('smartmirror')
self.tFrame = Frame(self.tk , bg='black')
self.tFrame.pack(side=TOP, fill=BOTH, expand=YES)
self.bFrame = Frame(self.tk, bg='black')
self.bFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
self.state = False
self.tk.bind("<Return>", self.toggle_fullscreen)
self.tk.bind("<Escape>", self.end_fullscreen)
#self.logo = Logo(self.topFrame)
#self.logo.pack(side=TOP,anchor=CENTER)
self.clock = Clock(self.tFrame)
self.clock.pack(side=RIGHT, anchor=NE, padx=50, pady=60) #side=RIGHT, anchor=NE, padx=50, pady=60
self.weather = Weather(self.tFrame)
self.weather.pack(side=LEFT, anchor=NW, padx=50, pady=25) #side=LEFT, anchor=NW, padx=50, pady=25
self.news = News(self.bFrame)
self.news.pack(side=LEFT, anchor=W, padx=25,pady=50)#side=LEFT, anchor=W, padx=25,pady=50 #new news
self.calendar = Calendar(self.bFrame)
self.calendar.pack(side=RIGHT,anchor=E,padx=110,pady=50)#side=RIGHT,anchor=E,padx=110,pady=50 #new calendar
self.quotes = Quotes(self.bFrame)
self.quotes.pack(side=RIGHT, anchor=E, padx=25, pady=40)
def toggle_fullscreen(self, event=None):
self.state = not self.state # Just toggling the boolean
self.tk.attributes("-fullscreen", self.state)
return "break"
def end_fullscreen(self, event=None):
self.state = False
self.tk.attributes("-fullscreen", False)
return "break"
if __name__ == '__main__':
w = FullscreenWindow()
w.tk.mainloop

Categories

Resources