Placement of tkinter Frame python - 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

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 get tkinter messagebox pop in front of toplevel in class

Is there a way to get the messagebox to appear in front of the toplevel?
code:
showwarning('warning','input four parameters!') shows the messagebox in front of mainwindow not toplevel window.
I checked the similar question root = Tk() texto = Toplevel(root) showinfo("title", "message") and the solution is ,showinfo("title", "message",parent=texto)
while I use class,there is no parent defination.
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *
import os
currentpath=os.path.dirname(__file__)
class AcurateQueryWindow(Toplevel):
def __init__(self,all_node_list:list):
super().__init__()
self.title("AcurateQuery")
self.width = 600
self.heigh = 500
self.screenwidth = self.winfo_screenwidth()
self.screenheight = self.winfo_screenheight()
self.geometry('%dx%d+%d+%d'%(self.width, self.heigh, (self.screenwidth-self.width)/2, (self.screenheight-self.heigh)/2))
self.resizable(0,0)
self.focus_set()
self.all_node_list = all_node_list
self.acurate_query_node_list=[]
self.setup_UI()
def setup_UI(self):
self.Style01 = Style()
self.Style01.configure("title.TLabel", font=("Helvetica", 25, "bold"), foreground="navy")
self.Style01.configure("pass.TLabel", font=("Helvetica", 15, "bold"), foreground="navy")
self.Style01.configure("TButton", font=("Helvetica", 12, "bold"))
self.Login_image = PhotoImage(file=currentpath+ os.sep + "img" + os.sep + "stu_detail_banner.png")
self.Label_image = Label(self, image=self.Login_image)
self.Label_image.pack()
# title
self.Label_title = Label(self, text="==AcurateQuery==", style="title.TLabel")
self.Label_title.place(x=280, y=15)
# pane
self.Pane_detail = PanedWindow(self, width=590, height=380)
self.Pane_detail.place(x=5, y=88)
#
self.Label_rlinemin = Label(self.Pane_detail,text = "rlinemin:",style = "pass.TLabel")
self.Label_rlinemin.place(x=160,y=70)
self.var_rlinemin = StringVar()
self.Entry_rlinemin = Entry(self.Pane_detail,textvariable = self.var_rlinemin , font=("Helvetica", 15, "bold"),width = 12)
self.Entry_rlinemin.place(x=280,y=68)
#
self.Label_rlinemax = Label(self.Pane_detail, text="rlinemax:",style = "pass.TLabel")
self.Label_rlinemax.place(x=160, y=120)
self.var_rlinemax = StringVar()
self.Entry_rlinemax = Entry(self.Pane_detail,textvariable=self.var_rlinemax, font=("Helvetica", 15, "bold"), width=12)
self.Entry_rlinemax.place(x=280, y=118)
#
self.Label_rpointmin = Label(self.Pane_detail, text="rpointmin:",style = "pass.TLabel")
self.Label_rpointmin.place(x=160, y=170)
self.var_rpointmin = StringVar()
self.Entry_rpointmin = Entry(self.Pane_detail,textvariable=self.var_rpointmin, font=("Helvetica", 15, "bold"), width=12)
self.Entry_rpointmin.place(x=280, y=168)
#
self.Label_rpointmax = Label(self.Pane_detail, text="rpointmax:",style = "pass.TLabel")
self.Label_rpointmax.place(x=160, y=220)
self.var_rpointmax = StringVar()
self.Entry_rpointmax = Entry(self.Pane_detail,textvariable=self.var_rpointmax, font=("Helvetica", 15, "bold"), width=12)
self.Entry_rpointmax.place(x=280, y=218)
#
self.Button_save = Button(self, text="query", style="TButton",command = self.query)
self.Button_save.place(x=300, y=452)
self.Button_exit = Button(self, text="close", style="TButton",command = self.close_window)
self.Button_exit.place(x=450, y=452)
def close_window(self):
self.destroy()
def query(self):
if len(self.Entry_rlinemin.get())==0 or len(self.Entry_rlinemax.get())==0 or len(self.Entry_rpointmin.get())==0 or len(self.Entry_rpointmax.get())==0:
showwarning('warning','input four parameters!')
pass
else:
rlinemin=int(str(self.Entry_rlinemin.get()).strip())
rlinemax=int(str(self.Entry_rlinemax.get()).strip())
rpointmin=int(str(self.Entry_rpointmin.get()).strip())
rpointmax=int(str(self.Entry_rpointmax.get()).strip())
if rlinemin>rlinemax or rpointmin>rpointmax:
showwarning('warning','max must bigger than min')
else:
self.acurate_query_node_list.append([rlinemin,rlinemax,rpointmin,rpointmax])
self.destroy()
return self.acurate_query_node_list
Is there a way to get the messagebox to appear in front of the toplevel while I use class?

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.

How can i erase contents in a Label?

Sorry for the mess
so I am making a seating chart, and I cant seem to get it working properly... again. I am trying to make the label reset every time i press the run button, any ideas?
#commands: add name , Run
#imports
import random
from time import sleep
from tkinter import *
#Console and background Handlers
Tables = 6
Names = []
def AddNames():
NewNames = e.get("1.0", 'end -1c')
if NewNames in Names:
print("Name Already exists")
elif NewNames == "":
print("Empty")
else:
Names.append(NewNames)
print(Names)
e.delete(1.0, END)
def Random():
RandomNum = random.randrange(Tables)
if RandomNum == 0:
RandomNum = random.randrange(Tables)
return RandomNum
def run():
X = 0
for i in Names:
#print(Names[X])
print("Table: " + str(Random()))
X += 1
#text = Label(popup, text = "")
text = Label(popup, text= Names[X] + "\n" + "Table: " + str(Random()))
text.pack()
#GUI Handler
root = Tk()
root.geometry("1024x768")
e = Text(root, bd = 10, font=("Comic Sans MS", 50) ,width = 15, height = 2)
e.pack()
popup = Toplevel()
popup.title("Seating Chart")
AddNameButton = Button(root, text = ("Add Name"), width = 15, height = 5, command = AddNames)
AddNameButton.pack()
RunButton = Button(root, text = ("Run"), width = 15, height = 5, command = run)
RunButton.pack()
root.mainloop()
I am trying to reset text every time the user presses the run button
import tkinter
from tkinter import ttk
import random
class MyApp:
def __init__(self):
self.root = tkinter.Tk()
self.seatwindow = None
self.root.title('Add Names')
self.currentname = tkinter.StringVar()
self._maxtables = tkinter.StringVar()
self.addednames = []
self.commandframe = ttk.Labelframe(self.root, text='Commands')
self.nameentry = ttk.Entry(self.root, textvariable=self.currentname)
self.addbutton = ttk.Button(self.root, text='Add Name', command=self.addname)
self.maxtablabel = ttk.Label(self.root, text='Tables: ')
self.maxtabentry = ttk.Entry(self.root, textvariable=self._maxtables)
self.genbutton = ttk.Button(self.commandframe, text='Run', command=self.generate)
self.resetbutton = ttk.Button(self.commandframe, text='Reset', command=self.reset)
self._maxtables.set('6')
self.nameentry.grid(row=0, column=0)
self.addbutton.grid(row=0, column=1, sticky='nsew')
self.maxtabentry.grid(row=1, column=1, sticky='nsw')
self.maxtablabel.grid(row=1, column=0, sticky='nse')
self.genbutton.grid(row=0, column=0, sticky='nsew')
self.resetbutton.grid(row=0, column=1, sticky='nsew')
self.commandframe.grid(row=2, column=0, columnspan=2, sticky='nsew')
self.nameentry.bind('<Return>', self.addname)
self.root.bind('<Control-Return>', self.generate)
def addname(self, event=None):
name = self.currentname.get()
if not(name == '' or name in self.addednames):
self.addednames.append(name)
self.currentname.set('')
else:
self.currentname.set('Name already added!')
def generate(self, event=None):
if not self.seatwindow == None:
self.seatwindow.destroy()
self.currentname.set('')
self.seatwindow = tkinter.Toplevel()
random.shuffle(self.addednames)
tables = []
for i in range(self.maxtables):
tableframe = ttk.Labelframe(self.seatwindow, text='Table ' + str(i + 1) + ':')
tableframe.grid(column=i, row=0, sticky='nsew')
tables.append(tableframe)
for index, name in enumerate(self.addednames):
namelabel = ttk.Label(tables[index%self.maxtables], text=name)
namelabel.grid(column=0, row=index//self.maxtables + 1)
def reset(self):
self.currentname.set('')
self.maxtables = 6
self.addednames = []
def run(self):
self.root.mainloop()
#property
def maxtables(self):
return int(self._maxtables.get())
MyApp().run()

Tkinter/class variable/method/widget.get() from another class issue in python 2.7

I am attempting to write a python program that utilizes Tkinter window switching OOP classes. On the starting page, there is an entry form where the user fills in the relevant fields. After filling the form the button 'to tests' is clicked where the user can select the test after switching frame/window, and the user information entered is simultaneously saved in the specified directory as a .txt file as a result of this button running several methods in class Startpage. The problem occurs when data is received by clicking on the yes or no buttons in the test 1 page.
This page operates in a different class, yet requires a return value from method get_info() defined in the Startpage class to get the user information (filename) entered to create a second .txt file to store raw data, storing appended 'yes' or 'no' strings depending on the button clicked in test 1's GUI window.
However this file is never created since Test1 is not receiving any entry data from Startpage class/window, therefore cannot assign a filename (call the get_info() containing the widget.get() functions) for the second .txt file.
The information is obtained in by the methods in the class correctly and everything works fine. However the problem arises when Test1 asks to receive the widget.get() variables/methods from Startpage.
The error thrown is the following IndexError:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Rylan\Anaconda\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:/Users/Rylan/Documents/Python/Basel Summerintern files/code to help with question.py", line 280, in update_countyes
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_t_info())
File "C:/Users/Rylan/Documents/Python/Basel Summerintern files/code to help with question.py", line 304, in get_t_info
self.gettheinfo = Startpage(app, self.controller).get_info()
File "C:/Users/Rylan/Documents/Python/Basel Summerintern files/code to help with question.py", line 170, in get_info
str(Day) + "_" + str(Month) + "_" +
IndexError: string index out of range
I am very new to OOP programming and to my knowledge this could be caused by:
Not properly referring/calling the Startpage instance, therefore the variables are not received by the Test1, therefore calling the get_info() method results in with nothing received by the nested widget.get() functions/variables in get_info() method.
Basically, what is the reason for this IndexError and how do I fix it to get the filename created/returned from the get_info() method in class Startpage sent to/called by class Test1?
I have seen similar questions relating to class variable and method calling from a different class, however none of which consider the case for window/frame switching Tkinter applications.
Here is the simplified code below (might not seem like it) which is able to be run (you may have directory path existence issues, just change path to whatever can be easily located for you to save the .txt files)
import Tkinter as tk
import ttk
import os
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)
def center(win):
"""
centers a tkinter window
param win: the window to center on the screen
"""
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
def popupmsg(msg):
popup1 = tk.Tk()
center(popup1)
popup1.minsize(width=60, height=70)
popup1.maxsize(width=60, height=70)
popup1.wm_title("Attention!")
label = ttk.Label(popup1, text=msg, font=NORM_FONT, anchor="center")
label.pack(side="top", fill="x", pady=10)
b1 = ttk.Button(popup1, text="Ok", command=lambda: popup1.destroy())
b1.pack()
popup1.mainloop()
class Testapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default="testappicon2.ico")
tk.Tk.wm_title(self, "Psychoacoustic Tests")
container = ttk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_columnconfigure(0, weight=1)
container.grid_rowconfigure(0, weight=1)
menubar = tk.Menu(container)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=lambda: self.destroy())
menubar.add_cascade(label="File", menu=filemenu)
tk.Tk.config(self, menu=menubar)
self.frames = {}
for F in (Startpage, TestSelect, Test1):
frame = F(container, self)
self.frames[F] = frame
self.minsize(width=900, height=500)
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Startpage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class Startpage(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
self.titlelabel = ttk.Label(self, text="User Information", font = LARGE_FONT)
self.titlelabel.grid(row=0, column=0, columnspan=4, padx = 10, pady = 10)
self.firstnamelabel = ttk.Label(self, text="First Name: ", font = NORM_FONT)
self.firstnamelabel.grid(row=1, column=0, sticky = 'w', padx = 15, pady = 10)
self.lastnamelabel = ttk.Label(self, text="Last Name: ", font = NORM_FONT)
self.lastnamelabel.grid(row=2, column=0, sticky = 'w', padx = 15, pady = 10)
self.firstnameentry = ttk.Entry(self)
self.firstnameentry.grid(row=1, column=1, padx=5, sticky = 'we', columnspan = 3)
self.lastnameentry = ttk.Entry(self)
self.lastnameentry.grid(row=2, column=1, padx=5, sticky = 'we', columnspan = 3)
self.birthdaylabel = ttk.Label(self, text="Birthday: ", font = NORM_FONT)
self.birthdaylabel.grid(row=3, column=0, sticky = 'w', padx = 15, pady = 10)
self.daydropdown = ttk.Combobox(self, justify='center', height=20, width=2,
values = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25,
26,27,28,29,30,31),
state='readonly')
self.daydropdown.grid(row=3, column=1, padx = 3, sticky = 'ew')
self.monthdropdown = ttk.Combobox(self, justify='center', height=12, width=10,
values = ('January','Feburary','March',
'April','May','June','July',
'August','September','October',
'November','December'),
state='readonly')
self.monthdropdown.grid(row=3, column=2, padx=3, sticky = 'ew')
self.yeardropdown = ttk.Combobox(self, justify='center', height=20, width=4,
values = (1980, 1981, 1982, 1983, 1984,
1985, 1986, 1987, 1988, 1989,
1990, 1991, 1992, 1993, 1994,
1995, 1996, 1997, 1998, 1999),
state = 'readonly')
self.yeardropdown.grid(row=3, column=3, padx = 3, sticky = 'ew')
self.genderlabel = ttk.Label(self, text="Gender: ", font = NORM_FONT)
self.genderlabel.grid(row=4, column=0, sticky = 'w', padx = 15, pady = 10)
self.var = tk.IntVar()
self.Maleradio = ttk.Radiobutton(self, text='Male', variable=self.var, value = 1)
self.Maleradio.grid(row=4, column=1, sticky = 'w')
self.Femaleradio = ttk.Radiobutton(self, text='Female', variable=self.var, value = 2)
self.Femaleradio.grid(row=5, column=1, sticky = 'w')
self.emaillabel = ttk.Label(self, text="Email: ", font = NORM_FONT)
self.emaillabel.grid(row=6, column=0, sticky = 'w', padx = 15, pady = 10)
self.emailentry = ttk.Entry(self)
self.emailentry.grid(row=6, column=1, columnspan=3, sticky='ew')
self.experiencelabel = ttk.Label(self, text="Musical Experience: ", font = NORM_FONT)
self.experiencelabel.grid(row=7, column=0, sticky = 'w', padx = 15, pady = 10)
self.expdropdown = ttk.Combobox(self, justify='center', height=3, width=17,
values = ('No experience', 'Some experience',
'Musician level'), state='readonly')
self.expdropdown.grid(row=7, column=1, columnspan=3, sticky = 'w')
self.button1 = ttk.Button(self, text="To Tests", command= lambda: self.checkempty())
self.button1.grid(row=8, column=3)
def shortcut():
controller.show_frame(TestSelect)
buttonshort = ttk.Button(self, text="To Tests shortcut", command= lambda: shortcut())
buttonshort.grid(row=9, column=3)
def get_info(self):
Name = self.firstnameentry.get()
Surname = self.lastnameentry.get()
Day = self.daydropdown.get()
Month = self.monthdropdown.get()
Year = self.yeardropdown.get()
foldername = (str(Name[0]) + str(Surname[0]) +
str(Day) + "_" + str(Month) + "_" +
str(Year))
return foldername
def create_directory(self):
if not os.path.isdir(self.get_info()):
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_info())
os.makedirs(directory)
datafile = "{}_userinfo.txt".format(self.get_info())
entirefile = os.path.join(directory, datafile)
myfile = open(entirefile, 'w')
myfile.write(self.userinfo())
myfile.close()
self.controller.show_frame(TestSelect)
else:
popupmsg("Folder already exists")
def userinfo(self):
Name = self.firstnameentry.get()
Surname = self.lastnameentry.get()
Day = self.daydropdown.get()
Month = self.monthdropdown.get()
Year = self.yeardropdown.get()
Email = self.emailentry.get()
Experience = self.expdropdown.get()
def genderget():
Gender = self.var.get()
if Gender == 1:
UserGender = "Male"
elif Gender == 2:
UserGender = "Female"
return UserGender
user_info = ("Participant Name: " + str(Name) + " " +
str(Surname) + "\nBirthday: " + str(Day) + "_" +
str(Month) + "_" + str(Year) + "\nGender: " +
str(genderget()) + "\nEmail: " + str(Email) +
"\nMusical Experience: " + str(Experience) +
"\nDirectory Name: " + str(self.get_info()))
return user_info
def checkempty(self):
Name = self.firstnameentry.get()
Surname = self.lastnameentry.get()
Day = self.daydropdown.get()
Month = self.monthdropdown.get()
Year = self.yeardropdown.get()
Email = self.emailentry.get()
Experience = self.expdropdown.get()
if len(Name) == 0:
popupmsg("Please complete the user information form")
elif len(Surname) == 0:
popupmsg("Please complete the user information form")
elif Day == None:
popupmsg("Please complete the user information form")
elif Month == None:
popupmsg("Please complete the user information form")
elif Year == None:
popupmsg("Please complete the user information form")
elif self.var.get() == 0:
popupmsg("Please complete the user information form")
elif len(Email) == 0:
popupmsg("Please complete the user information form")
elif Experience == None:
popupmsg("Please complete the user information form")
else:
self.create_directory()
class TestSelect(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
label = ttk.Label(self, text="Select tests", font = LARGE_FONT)
label.grid(row=0, column=0, columnspan=3)
Test1Button = ttk.Button(self, text="Do test 1", command=lambda: controller.show_frame(Test1))
Test1Button.grid(row=1, column=0, padx = 20, pady = 15, sticky = 'nsew')
button2 = ttk.Button(self, text="Home", command=lambda: controller.show_frame(Startpage))
button2.grid(row=3, column=2)
class Test1(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
self.controller = controller
label = ttk.Label(self, text="Test 1", font = LARGE_FONT)
label.grid(row=0, column=0, columnspan=2)
button2 = ttk.Button(self, text="Page one", command=lambda: controller.show_frame(TestSelect))
button2.grid(row=1, column=0, sticky = "w")
yesbutt1 = ttk.Button(self)
yesbutt1.grid(row=2, column=0)
nobutt1 = ttk.Button(self)
nobutt1.grid(row=2, column=1)
yesbutt1['text'] = "Yes: 0"
nobutt1['text'] = "No: 0"
self.nobttn_clicks = 0
self.yesbttn_clicks = 0
def update_countyes():
if self.yesbttn_clicks >= 1 or self.nobttn_clicks >= 1:
popupmsg("Only one answer allowed!")
else:
self.yesbttn_clicks += 1
yesbutt1['text'] = "Yes: " + str(self.yesbttn_clicks)
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_t_info())
datafile = "{}_test1data.txt".format(self.get_t_info())
entirefile = os.path.join(directory, datafile)
myfile = open(entirefile, 'a')
myfile.write('\nyes')
myfile.close()
def update_countno():
if self.yesbttn_clicks >= 1 or self.nobttn_clicks >= 1:
popupmsg("Only one answer allowed!")
else:
self.nobttn_clicks += 1
nobutt1['text'] = "No: " + str(self.nobttn_clicks)
directory = "C:\Users\Rylan\Documents\Python\Basel Summerintern files\{}".format(self.get_t_info())
datafile = "{}_test1data.txt".format(self.get_t_info())
entirefile = os.path.join(directory, datafile)
myfile = open(entirefile, 'a')
myfile.write('\nno')
myfile.close()
yesbutt1['command'] = update_countyes
nobutt1['command'] = update_countno
def get_t_info(self):
self.gettheinfo = Startpage(app, self.controller).get_info()
return self.gettheinfo
app = Testapp()
app.mainloop()
Your problem is that when you write:
def get_t_info(self):
self.gettheinfo = Startpage(app, self.controller).get_info()
return self.gettheinfo
you create a new StartPage where the Entries are empty.
Then
Name = self.firstnameentry.get()
...
foldername = (str(Name[0])
tries to get the first character of an empty string.
I think the solution should be something like:
def get_t_info(self):
return self.controller.frames[Startpage]

Categories

Resources