I am trying to collect the date from a calendar widget in tkinter using a button and then display that date in a label, so I defined a function to do so, however, it does not work and I get the error message "getdate() missing 2 required positional arguments: 'self' and 'cont'"\
I am not sure why this is as I have included self and cont in the function brackets.
import tkinter as tk
from tkinter import ttk
from tkcalendar import *
def getdate(self, cont):
date_label.config(text="Today's date is " + cal.get_date()) #function to get date from
#calendar and display in label
#window = Tk()
#window.title("StudyFriendO")
LARGE_FONT= ("Verdana", 24)
class StudyFriendO(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("StudyFriendO") #naming window title
self.geometry('850x830') #size of window
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, HomePage, ToDoPage, TimetablePage): #list of multiple frames of program
frame = F(container, self)
self.frames[F] = frame
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(tk.Frame): #creating start page
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="StudyFriendO", font = LARGE_FONT, bg="#f2fcff")
label.pack(fill="x")
#place(x=315,y=100)
photo1 = tk.PhotoImage(file NAME') #photo1 is a variable
#label (window, image=photo1, bg="black") .grid(row=0, column=0, sticky=E)
panel = tk.Label(self, image = photo1)
panel.image = photo1
panel.pack(fill="x")
#place(x=270,y=150)
label2 = tk.Label(self, text="Enter today's date and your first name below:", bg="#f2fcff")
label2.pack(fill="x", ipady=20)
#place(x=305, y=400)
cal = Calendar(self, background="#e0f6fc", disabledbackground="white", bordercolor="light blue", headersbackground="light blue", normalbackground="#e0f6fc", foreground="black", normalforeground='black', headersforeground='white', selectmode="day", year=2021, month=8, day=9)
cal.place(relx=0.5, rely=0.5, anchor='center')
#(x=300,y=430) #calendar
nameentry = tk.Entry(self, width=20, bg="white") #text input for users name
nameentry.place(relx=0.5, rely=0.68, anchor='center')
#(x=365, y=635)
caldate = ttk.Button(self, text="Submit",
command=getdate) #button to get current date
caldate.place(relx=0.5, rely=0.63, anchor='center')
button1 = ttk.Button(self, text="Enter",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.place(relx=0.5, rely=0.73, anchor='center')
#(x=387,y=660)
date_label = tk.Label(self, text="") #label to display date
date_label.pack(pady=20)
self.configure(bg='#f2fcff')
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Home", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="To Do",
command=lambda: controller.show_frame(ToDoPage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Timetable",
command=lambda: controller.show_frame(TimetablePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.pack()
class ToDoPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="To Do", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Timetable",
command=lambda: controller.show_frame(TimetablePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="To Do",
command=lambda: controller.show_frame(ToDoPage)) #button to navigate page
button1.pack()
class TimetablePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Timetable", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Timetable",
command=lambda: controller.show_frame(TimetablePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="To Do",
command=lambda: controller.show_frame(ToDoPage)) #button to navigate page
button1.pack()
app = StudyFriendO()
app.mainloop()
There were a couple of issues with the given questions.
There is no reference for date_label & cal inside the get_date() function. cal may be an import error.
Moved get_date() inside the StudyFriendO class & renamed it to set_date().
modified the way to handled this as a command from the submit button.
Have a look at the modified code & the output image.
import calendar
import tkinter as tk
from tkinter import ttk
from tkcalendar import *
from datetime import datetime
#calendar and display in label
#window = Tk()
#window.title("StudyFriendO")
LARGE_FONT= ("Verdana", 24)
class StudyFriendO(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("StudyFriendO") #naming window title
self.geometry('850x830') #size of window
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, HomePage, ToDoPage, TimetablePage): #list of multiple frames of program
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def set_date(self, cont):
frame: StartPage = self.frames[cont]
frame.date_label.config(text="Today's date is " + datetime.today().strftime("%B %d, %Y")) #function to get date from
class StartPage(tk.Frame): #creating start page
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="StudyFriendO", font = LARGE_FONT, bg="#f2fcff")
label.pack(fill="x")
#place(x=315,y=100)
photo1 = tk.PhotoImage(file="1.png") #photo1 is a variable
#label (window, image=photo1, bg="black") .grid(row=0, column=0, sticky=E)
panel = tk.Label(self, image = photo1)
panel.image = photo1
panel.pack(fill="x")
#place(x=270,y=150)
label2 = tk.Label(self, text="Enter today's date and your first name below:", bg="#f2fcff")
label2.pack(fill="x", ipady=20)
#place(x=305, y=400)
cal = Calendar(self, background="#e0f6fc", disabledbackground="white", bordercolor="light blue", headersbackground="light blue", normalbackground="#e0f6fc", foreground="black", normalforeground='black', headersforeground='white', selectmode="day", year=2021, month=8, day=9)
cal.place(relx=0.5, rely=0.5, anchor='center')
#(x=300,y=430) #calendar
nameentry = tk.Entry(self, width=20, bg="white") #text input for users name
nameentry.place(relx=0.5, rely=0.68, anchor='center')
#(x=365, y=635)
caldate = ttk.Button(self, text="Submit",
command=lambda: controller.set_date(StartPage)) #button to get current date
caldate.place(relx=0.5, rely=0.63, anchor='center')
button1 = ttk.Button(self, text="Enter",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.place(relx=0.5, rely=0.73, anchor='center')
#(x=387,y=660)
self.date_label = tk.Label(self, text="") #label to display date
self.date_label.pack(pady=20)
self.configure(bg='#f2fcff')
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Home", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="To Do",
command=lambda: controller.show_frame(ToDoPage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Timetable",
command=lambda: controller.show_frame(TimetablePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.pack()
class ToDoPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="To Do", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Timetable",
command=lambda: controller.show_frame(TimetablePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="To Do",
command=lambda: controller.show_frame(ToDoPage)) #button to navigate page
button1.pack()
class TimetablePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Timetable", font = LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(HomePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="Timetable",
command=lambda: controller.show_frame(TimetablePage)) #button to navigate page
button1.pack()
button1 = ttk.Button(self, text="To Do",
command=lambda: controller.show_frame(ToDoPage)) #button to navigate page
button1.pack()
app = StudyFriendO()
app.mainloop()
Output Image:
Related
I'm sure i'm missing something with the class/inheritence understanding.
when i hit the submit button i get this error:
I tried many variations like changing the command in the button, changing masters, defining self.controller.
how can I make the submit button to work?
import tkinter as tk
import os
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("650x500")
self.title("Gil Shwartz GUI Project")
menu = tk.Frame(self, height=250, width=10, bg="black")
menu.pack(side=tk.LEFT, fill="both", anchor="w")
container = tk.Frame(self, height=250, width=270, relief="flat")
container.pack(side=tk.TOP, fill="both", expand=True)
output = tk.LabelFrame(self, text="Output", height=150, padx=5, pady=5)
output.pack(side=tk.BOTTOM, fill="both", anchor="s")
menu.grid_columnconfigure(0, weight=0)
menu.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(1, weight=1)
self.frames = ["StartPage", "MainWelcome", "testPing", "PageOne", "PageTwo"]
self.frames[0] = Menu(parent=menu, controller=self)
self.frames[1] = MainWelcome(parent=container, controller=self)
self.frames[2] = testPing(parent=container, controller=self)
self.frames[3] = PageOne(parent=container, controller=self)
self.frames[4] = PageTwo(parent=container, controller=self)
self.frames[0].grid(row=0, column=0, sticky="nsew")
self.frames[1].grid(row=0, column=0, sticky="nsew")
self.frames[2].grid(row=0, column=0, sticky="nsew")
self.frames[3].grid(row=0, column=0, sticky="nsew")
self.frames[4].grid(row=0, column=0, sticky="nsew")
self.show_frame(1)
def show_frame(self, page_name):
frame = self.frames[page_name]
print(frame)
frame.tkraise()
class Menu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.menu = controller
button1 = tk.Button(self, text="Ping Test",
command=lambda: controller.show_frame(2))
button2 = tk.Button(self, text="Page Two",
command=lambda: controller.show_frame(4))
button3 = tk.Button(self, text="Quit",
command=lambda: Menu.terminate(self))
button1.pack(fill="both", expand=True)
button2.pack(fill="both", expand=True)
button3.pack(fill="both", expand=True)
button1.grid_columnconfigure(0, weight=1)
button2.grid_columnconfigure(0, weight=0)
button3.grid_rowconfigure(0, weight=0)
def terminate(self):
exit()
class MainWelcome(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.menu = controller
label = tk.Label(self, text="Text 1", bg="yellow")
label.pack(fill="x", expand=True)
label = tk.Label(self, text="Text 2", bg="yellow")
label.pack(fill="x")
class testPing(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.urlLabel = controller
urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
urlLabel.pack(anchor="w")
urlInputBox = tk.Entry(self)
urlInputBox.pack()
urlInputBox.grid_columnconfigure(0, weight=0)
clearLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
clearLabel.pack(anchor="w")
clearFile = tk.BooleanVar()
clearFile.set(False)
clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
command=lambda: testPing.callback(clearFile.get()))
clearFileRadioYes.pack(anchor="w")
clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
command=lambda: testPing.callback((clearFile.get())))
clearFileRadioNo.pack(anchor="w")
urlSubmitButton = tk.Button(self, text="Submit",
command=lambda: testPing.pingURL(urlInputBox.get(),
testPing(clearFile.get())))
urlSubmitButton.pack(side=tk.RIGHT, anchor="e")
def callback(clearFile):
print(clearFile) # Debugging Mode - check Radio box Var.
def pingURL(self, host, clearFile):
outputFrameLabel = tk.LabelFrame(self, text="Output", height=35, width=150,
padx=5, pady=5, relief="solid")
outputFrameLabel.place(x=0, y=150)
file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
label = tk.Label(outputLabel, text=f'Pinging {host} ...')
label.grid(row=0, column=0)
label.update()
if clearFile == True:
with open(file, 'w+') as output:
output.truncate(0)
sub.call(['ping', f'{host}'], stdout=output)
else:
with open(file, 'a') as output:
sub.call(['ping', f'{host}'], stdout=output)
output.close()
label.configure(text=f'Ping to {host} complete!')
# testPing.changeLabel(host)
# def changeLabel(self, host):
# myLabel = tk.Label.config(text=f"Ping to {host} Complete!")
# myLabel.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", bg="red")
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to page 2",
command=lambda: controller.show_frame(2))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", bg="blue")
label.pack(side="top", fill="x", pady=10)
# button = tk.Button(self, text="Go to the start page",
# command=lambda: controller.show_frame(0))
# button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
here's a pic of the main window so you'll get a visual idea as well.
I think the error lies in the testPing class; in particular in these lines:
class testPing(tk.Frame):
...
clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
command=lambda: testPing.callback(clearFile.get()))
clearFileRadioYes.pack(anchor="w")
clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
command=lambda: testPing.callback((clearFile.get())))
clearFileRadioNo.pack(anchor="w")
urlSubmitButton = tk.Button(self, text="Submit",
command=lambda: testPing.pingURL(urlInputBox.get(),
testPing(clearFile.get())))
You're inside testPing, so you should use self instead of using testPing explicitly. So, your code should be:
class testPing(tk.Frame):
...
clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
command=lambda: self.callback(clearFile.get()))
clearFileRadioYes.pack(anchor="w")
clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
command=lambda: self.callback((clearFile.get())))
clearFileRadioNo.pack(anchor="w")
urlSubmitButton = tk.Button(self, text="Submit",
command=lambda: self.pingURL(urlInputBox.get(),
clearFile.get()))
Notice using self instead of testPing
I am VERY new to coding/Python, but basically I am trying to move a button and label around using .grid, however, the button and label in the StartPage class just won't move to where I ask (or even at all).
Everything in the BMR class works fine (although the positions you see aren't the final positions, I was just checking).
What is the difference? Why do they not appear at the same position if I give the same details in both classes?
import tkinter as tk
class initials(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side='top', fill='both', expand= True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, BMR):
frame = F(container, self)
self.frames[F] = frame
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(tk.Frame): #GRID WON'T WORK HOW I WANT IT TO
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Start Page")
label.grid(column=3, row=3, sticky='we')
button = tk.Button(self, text="Calculate BMR",
command=lambda: controller.show_frame(BMR))
button.grid(row=4, column=3, sticky='we')
class BMR(tk.Frame): #GRID WORKS PERFECTLY
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="BMR Calculator")
label.grid(column=1,row=1)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.grid(column=2, row=2)
submit = tk.Button(self, text="Calculate")
submit.grid(column=3, row=3)
var1 = tk.IntVar()
tk.Checkbutton(self, text='Male', bg='white', variable=var1).grid(column=4, row=4)
var2= tk.IntVar()
tk.Checkbutton(self, text='Female', bg='white', variable=var2).grid(column=5, row=5)
height_inp = tk.Entry(self, width=20, bg="white").grid(column=6, row=6)
app = initials()
app.mainloop()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Start Page", width = 80)
# Added width property in the line above
# and changed sticky property to N
label.grid(row = 3, column=3, sticky = 'N')
label.width = 20
button = tk.Button(self, text="Calculate BMR",
command=lambda: controller.show_frame(BMR))
button.grid(row=4, column=3)
# Removed sticky property for the button
I understand this is how you wish to position the label and the button.
Pleaase see the comments. You can edit the value for the width property and make it suitable for your frame.
I'm trying to create a simple GUI with tkinter with buttons and images. I have a startpage with an image and buttons that take you to other pages(frames). The problem is that the image in my startpage persists and displays in the other frames.
The code:
import tkinter as tk
LARGE_FONT = ("Verdana", 12)
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.geometry("800x480")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Start Page", font=LARGE_FONT)
label.pack(pady=10, padx=10)
#canvas1 = tk.Canvas(width=600, height=300, bg="gray")
#self.img = tk.PhotoImage(file="mario.png")
#canvas1.create_image(20, 20, image=self.img)
#canvas1.pack()
photo = tk.PhotoImage(file="mario.png")
labelimg = tk.Label(image=photo)
labelimg.image = photo # keep a reference!
labelimg.pack()
button = tk.Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = tk.Button(self, text="Visit Page 2",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text="Page One",
command=lambda: controller.show_frame(PageOne))
button2.pack()
app = SeaofBTCapp()
app.mainloop()
The issue is that you have not specified labelimg's parent therefore, by default it is the main window. As a consequence, your label is packed below your container and therefore is always visible.
Changing
labelimg = tk.Label(image=photo)
into
labelimg = tk.Label(self, image=photo)
in the class StartPage should solve your problem.
I am coding a program which will need functions to change labels and enter text into text boxes however I do not know how to do this with a new style of programming which I am using (Object Orientated). I have done the program before however I generated the frames using this code:
f = [Frame(root) for i in range(0,5)]
for i in f:
i.place(relx=0,rely=0,relwidth=1,relheight=1)
and then I put it all in one class which I ran however that was bad form so I am redoing it. My code so far is as follows:
import tkinter as tk
import datetime,time,os,sys
import sqlite3 as lite
from datetime import date
Title_Font= ("Times", 18, "underline italic")
unix = time.time()
time_curr = str(datetime.datetime.fromtimestamp(unix).strftime('%H:%M'))
date1 = str(datetime.datetime.fromtimestamp(unix).strftime('%d-%m-%Y'))
class Creating_Stuff(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
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(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
self.option_add( "*font", "Times 12" )
self.tk_setPalette(background='#bbfff0', foreground='black',
activeBackground='#d9d9d9', activeForeground='#ff9933')
label = tk.Label(self, text="Laptop Booking System", font=Title_Font)
label.grid(row=0, column=1, pady = 30)
time = tk.Label(self, text="Time: " + time_curr + "\nDate: " + date1, font="Times 10")
time.grid(row=0, column=2,columnspan=2)
Booking_1 = tk.Button(self, text="Booking",
command=lambda: controller.show_frame(PageOne),bg='#f2f2f2',width=20)
Booking_1.grid(row=2, column=1, pady=10)
Tbl_q1 = tk.Button(self, text="Table Querying",
command=lambda: controller.show_frame(PageTwo),bg='#f2f2f2',width=20)
Tbl_q1.grid(row=3, column=1, pady=10)
Exit = tk.Button(self, text ="Exit",command=lambda:destroy(),bg='#f2f2f2')
Exit.grid(row=5, column=1)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
label = tk.Label(self, text="Page One!!!", font=Title_Font)
label.grid(row=1, column=1)
bk2_menu = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
bk2_menu.grid(row=3, column=1)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
label = tk.Label(self, text="Page Two!!!", font=Title_Font)
label.grid(row=1, column=1)
bk2_Menu2 = tk.Button(self, text="Back to menu",
command=lambda: controller.show_frame(StartPage))
bk2_Menu2.grid(row=3, column=1)
app = Creating_Stuff()
def destroy():
app.destroy()
app.title("Laptop Booking System")
app.geometry("700x400")
app.mainloop()
If you try it out it works however it just has 3 different frames. How can I get a button in a frame to make a label say "Hello" in the frame after it is pressed?
I've modified one of your page classes to illustrate how it could be done. It involved adding a Label to hold the message, a Button to control it, and a function, called simply handler(), to call when the latter is pressed. It saves the widgets by making them attributes of the containing Frame subclass instance, self, so they can be easily referenced in the handler() function (without resorting to global variables).
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
label = tk.Label(self, text="Page One!!!", font=Title_Font)
label.grid(row=1, column=1)
self.msg_label = tk.Label(self, text="")
self.msg_label.grid(row=2, column=1)
self.msg_button = tk.Button(self, text='Show Message',
command=self.handler)
self.msg_button.grid(row=3, column=1)
self.msg_toggle = False
bk2_menu = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
bk2_menu.grid(row=5, column=1)
def handler(self):
self.msg_toggle = not self.msg_toggle
if self.msg_toggle:
self.msg_label.config(text='Hello')
self.msg_button.config(text='Clear Message')
else:
self.msg_label.config(text='')
self.msg_button.config(text='Show Message')
Screenshots
Before button is pressed:
After button is pressed:
This question already has answers here:
How to get variable data from a class?
(2 answers)
Closed 6 years ago.
my program is this..
import tkinter as tk
from tkinter import *
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
self.title(" Allocation")
width, height = self.winfo_screenwidth(), self.winfo_screenheight()
self.geometry('%dx%d+0+0' % (width,height))
self.state('zoomed')
self.wm_iconbitmap('icon.ico')
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, c):
frame = self.frames[c]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
logo = tk.PhotoImage(file="backesh.ppm")
BGlabel = tk.Label(self,image=logo)
BGlabel.image = logo
BGlabel.place(x=0,y=0,width=592,height=450)
label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
label.place(x=0,y=0,width=592,height=44)
frame1 = Frame(self)
Label(frame1, bd=5,bg="black",text=" Enter text : ",font=("Helvetica", 14),fg="light green",width=21).pack(side=LEFT)
emp=Entry(frame1, bd =5,font=("Times New Roman", 14),width=25)
emp.pack(side=LEFT)
frame1.place(x=400,y=160)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button2 = tk.Button(self, text="Go to Page two",
command=lambda: controller.show_frame(PageTwo))
button3 = tk.Button(self, text="Exit",
command=self.quit)
button1.place(x=100,y=406,width=200,height=44)
button2.place(x=300,y=406,width=200,height=44)
button3.place(x=500,y=406,width=80,height=44)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
logo = tk.PhotoImage(file="backesh.ppm")
BGlabel = tk.Label(self,image=logo)
BGlabel.image = logo
BGlabel.place(x=0,y=0,width=592,height=450)
label = tk.Label(self, text="This is page one", font=TITLE_FONT)
label.place(x=0,y=0,width=592,height=44)
button1 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
#button2 = tk.Button(self, text="Go to Page two",
# command=lambda: controller.show_frame(PageTwo))
button3 = tk.Button(self, text="Exit",
command=self.quit)
button1.place(x=100,y=406,width=200,height=44)
button3.place(x=300,y=406,width=200,height=44)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
logo = tk.PhotoImage(file="backesh.ppm")
BGlabel = tk.Label(self,image=logo)
BGlabel.image = logo
BGlabel.place(x=0,y=0,width=592,height=450)
label = tk.Label(self, text="This is page two", font=TITLE_FONT)
label.place(x=0,y=0,width=592,height=44)
button1 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
#button2 = tk.Button(self, text="Go to Page two",
# command=lambda: controller.show_frame(PageTwo))
button3 = tk.Button(self, text="Exit",
command=self.quit)
button1.place(x=100,y=406,width=200,height=44)
button3.place(x=300,y=406,width=200,height=44)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
i want to take entry text data from StartPage and display it as label in PageOne. How to do it? I am new to this. Please type the code.
Thanks in advance.
Firstly, correct the code of the class PageOne and StartPage and add self.controller = controller to the __init__ function:
class PageOne(tk.Frame):
def __init__(self, parent, controller):
#your code
self.controler = controller
Add self before entry field in StartPage and before label in PageOne:
#entry in StartPage
self.emp=tk.Entry(frame1, bd =5,font=("Times New Roman", 14),width=25)
self.emp.pack(side=tk.LEFT)
#label in PageOne
self.label = tk.Label(self, text="This is page one", font=TITLE_FONT)
self.label.place(x=0,y=0,width=592,height=44)
Then add a function go_to_page_one to StartPage class:
def go_to_page_one(self):
self.controller.SomeVar = self.emp.get() #save text from entry to some var
self.controller.frames[PageOne].correct_label() #call correct_label function
self.controller.show_frame(PageOne) #show page one
On button1 in StartPage class change command to lambda: self.go_to_page_one():
button1 = tk.Button(self, text="Go to Page One",
command=lambda: self.go_to_page_one())
At last add a function correct label to the class PageOne:
def correct_label(self):
self.label.config(text=self.controller.SomeVar) #correct the label