I am using a solution found to try and share variables throughout my code, which consists of 'Frame' classes. However, any attempt I make to try and change the value of these shared variables seems to have no effect, and after I attempt to change them, if I print it just returns blank. Any help would be appreciated.
class GolfApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.shared_data = {
"currentcourse": tk.StringVar(),
"numberofteams": tk.IntVar()}
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 (MainMenu, CreatePage, ViewPage, GetTeamsPage, ChooseCourse,
AddCourse, LoginSignUp, Login, SignUp, Highscores1, Highscores2,
Scorecards1, Scorecards2):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("LoginSignUp")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
This is where the solution from the link can be found. I have two variables, 'currentcourse' and 'numberofteams' which I need to share from one frame to others. I am attempting to set these variables in two different classes in the following bits of code.
class GetTeamsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background="lightgreen")
def set_teamnumber():
numberofteams = answerentry.get()
numberofteams = self.controller.shared_data["numberofteams"].get()
def testInt(inStr, i, acttyp):
ind = int(i)
if acttyp == '1':
if not inStr[ind].isdigit():
return False
return True
for col in range(7):
self.grid_columnconfigure(col)
for row in range(5):
self.grid_rowconfigure(row)
questionlbl = tk.Label(self,
text="How many teams/players are there?",
bg="lightgreen",
font = "Verdana 20 bold")
questionlbl.grid(column=2,
row=0,
columnspan=3)
answerentry = tk.Entry(self,
text="Enter a number here.",
validate = "key",
textvariable=self.controller.shared_data["numberofteams"])
answerentry.grid(column=2,
row=2,
columnspan=3)
moveonbtn = tk.Button(self,
text="Continue",
height = "3",
width = "40",
bg="darkgreen",
fg="lightgreen",
command = lambda: (controller.show_frame("CreatePage"), set_teamnumber()))
moveonbtn.grid(column=1,
row=5,
columnspan=3)
returnbtn = tk.Button(self,
height="3",
width="40",
bg="darkgreen",
fg="lightgreen",
text="Return to main menu",
command = lambda: controller.show_frame("MainMenu"))
returnbtn.grid(column=4,
row=5,
columnspan=3)
class ChooseCourse(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background="lightgreen")
cursor.execute("SELECT CourseName FROM Course")
coursetuple = cursor.fetchall()
courselist = [row[0] for row in coursetuple]
def get_choice():
currentcourse = self.controller.shared_data["currentcourse"]
currentcourse = listmenu.get()
for col in range(2):
self.grid_columnconfigure(col, minsize=50)
for row in range(7):
self.grid_rowconfigure(row, minsize=60)
titlelbl = tk.Label(self,
text="Choose a course",
bg="lightgreen",
font = "Verdana 20 bold")
titlelbl.grid(column=2,
row=0)
addbtn = tk.Button(self,
text="Add a new course",
bg="darkgreen",
fg="lightgreen",
command = lambda: controller.show_frame("AddCourse"))
addbtn.grid(column=2,
row=3)
continuebtn = tk.Button(self,
text="Continue",
bg="darkgreen",
fg="lightgreen",
command = lambda: (controller.show_frame("GetTeamsPage"), get_choice))
continuebtn.grid(column=2,
row=4)
returnbtn = tk.Button(self,
text="Return to main menu",
bg="darkgreen",
fg="lightgreen",
command = lambda: controller.show_frame("MainMenu"))
returnbtn.grid(column=2,
row=5)
listmenu = tk.Listbox(self)
for x in range(0, len(courselist)):
listmenu.insert("end", courselist[x])
listmenu.grid(column=2,
row=1)
You start by setting shared_data["current_course"] to an instance of StringVar, but then later you're resetting it to just a string.
Since it is a StringVar, you need to call the set method to set the value:
currentcourse = self.controller.shared_data["currentcourse"]
currentcourse.set(listmenu.get())
Related
import tkinter as tk
class program(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args,**kwargs)
self.title("Staff Management System")
self.geometry("1280x720")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.frames = {}
#frame that will hold all the elements
container = tk.Frame(self)
container.grid(row=0,column=0, sticky="nsew")
container.columnconfigure(0,weight=1)
container.rowconfigure(0,weight=1)
container.configure(background="blue")
#listing frames (pages) to be controlled
for F in (homePage, staffLogin):
frame = F(parent=container, controller=self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(homePage)
def show_frame(self, page):
frame = self.frames[page]
frame.tkraise()
class homePage(tk.Frame):
def __init__(self, parent, controller, *args, **kwargs):
tk.Frame.__init__(self,parent,*args, **kwargs)
for i in range(5):
self.columnconfigure(i, weight=1)
for i in range(5):
self.rowconfigure(i, weight=1)
promotionsButton = tk.Button(self, text="Promotions", height = 4)
promotionsButton.grid(row=5, column =0, sticky='w')
staffLoginButton = tk.Button(self, text="Staff Login", width = 50, height = 20, command= lambda: controller.show_frame(staffLogin))
staffLoginButton.grid(row=2, column=1)
managerLoginButton = tk.Button(self, text="Manager Login", width = 50, height = 20)
managerLoginButton.grid(row=2,column=2)
class staffLogin(tk.Frame):
def __init__(self, parent, controller, *args, **kwargs):
tk.Frame.__init__(self,parent, *args, **kwargs)
self.controller = controller
for i in range(128):
self.columnconfigure(i,weight=1)
for i in range(128):
self.rowconfigure(i,weight=1)
self.staffLabel = tk.Label(self, text = "Staff Login", font=("Helvectia", 24))
self.staffLabel.grid(row = 40, column=60)
self.userIDLabel = tk.Label(self, text = "UserID:")
self.userIDLabel.grid(sticky="W", row=67,column=59)
self.userIDInput = tk.Entry(self, width=50, font=("Helvectia",16))
self.userIDInput.grid(row=67, column=60)
self.userPasswordLabel = tk.Label(self, text = "Password:")
self.userPasswordLabel.grid(sticky="W", row=70, column=59)
self.userPasswordInput = tk.Entry(self,width=50, font=("Helvectia",16))
self.userPasswordInput.grid(row=70, column=60)
self.showPassword = tk.Button(self, text="Show Password", command=self.togglePassword())
self.showPassword.grid(sticky="W", row=71, column=60)
self.loginButton = tk.Button(self, text="Login", height=2, width=7)
self.loginButton.grid(sticky="E",row = 71, column=60)
self.backButton = tk.Button(self, text="Back To Main Menu", height=4, command= lambda: controller.show_frame(homePage))
self.backButton.grid(row=128, column=0)
def togglePassword(self):
if self.userPasswordLabel.cget("show") == "*":
self.userPasswordLabel.config(show= "")
self.showPassword.config(text="Hide Password")
else:
self.userPasswordLabel.config(show="")
self.showPassword.config(text="Show Password")
thing = program()
thing.mainloop()
im trying to create a function that runs when clicked inside of my "staff login" page. However, due to me using a new method of programming tkinter to be able to switch pages, I am unsure of how to get functions for buttons to work. currently, i get an error saying that the methods that i am trying to call do not exist. im not sure of what to do in order to be able to run functions inside of pages
In my code, there are two frames. In the first one, I put in an Add button that will produce a new frame with a Combobox. The idea is to add a few Combobox like that in the first frame, pick different options for different Combobox, and then print them out in the next frame. But when I hit the Show options button in the second frame, it doesn't print out the options that I just chose in the first frame. How can I solve this?
from tkinter import *
from tkinter import ttk
list_1 = []
class Validation_Tool(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = 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 (PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("PageOne")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
def quit(self):
self.destroy()
class PageOne(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
def add_compare():
global list_1
frame = Frame(self)
frame.pack()
label_1 = Label(frame, text='Options')
label_1.grid(row=0, column=0)
self.options_1 = ttk.Combobox(frame, values=['a','b','c','d','e'])
self.options_1.grid(row=1, column=0)
list_1.append(self.options_1.get())
quit_button = Button(self, text="Quit Program",
command=lambda: controller.quit())
next_button = Button(self, text="Next",
command=lambda: controller.show_frame("PageTwo"))
add_button = Button(self, text='Add', command=add_compare)
quit_button.place(relx=0.98, rely=0.98, anchor=SE)
next_button.place(relx=0.76, rely=0.98, anchor=SE)
add_button.place(relx=0.661, rely=0.98, anchor=SE)
class PageTwo(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
def button():
label = Label(self, text=list_1)
label.pack()
quit_button = Button(self, text="Quit Program",
command=lambda: controller.quit())
back_button = Button(self, text="Back",
command=lambda: controller.show_frame("PageOne"))
show_button = Button(self, text='Show options', command=button)
show_button.pack()
back_button.place(relx=0.76, rely=0.98, anchor=SE)
quit_button.place(relx=0.98, rely=0.98, anchor=SE)
if __name__ == "__main__":
root = Validation_Tool()
root.geometry('400x300+430+250')
root.title("Validation Tool")
root.mainloop()
Here's a modified version of your code that will print the options selected so far when the Next is pressed. To prevent the Comboboxes from interferring with each other a list of them and an associated StringVars is kept.
Having separate StringVars avoids the problem of choosing an option on one of them from changing it on the others — i.e. a different textvar gets associated with each one.
To make collecting all the options together into list_1, a callback function named selected() has been defined and gets "bound" to Combobox selection events. This make it so that, in addition to the above, the option selected will also get appended to the global list_1, which is what the Show options button displays.
from tkinter import *
from tkinter import ttk
list_1 = []
class Validation_Tool(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.comboboxes = [] # Comboboxes created. ADDED
self.combobox_vars = [] # Vars for Comboboxes. ADDED.
self.frames = {}
for F in (PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("PageOne")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
def quit(self):
self.destroy()
class PageOne(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
# Combobox event handler. ADDED
def selected(event, var):
list_1.append(var.get()) # Append Combobox option selected.
def add_compare():
frame = Frame(self)
frame.pack()
label_1 = Label(frame, text='Options')
label_1.grid(row=0, column=0)
combobox_var = StringVar() # ADDED.
combobox = ttk.Combobox(frame, values=list('abcde'),
textvar=combobox_var) # For each Combobox. ADDED.
combobox.grid(row=1, column=0)
combobox.bind('<<ComboboxSelected>>', # Bind event handler. ADDED.
lambda event, var=combobox_var: selected(event, var)) # ADDED.
self.controller.comboboxes.append(combobox) # ADDED.
self.controller.combobox_vars.append(combobox_var) # ADDED.
quit_button = Button(self, text="Quit Program",
command=lambda: controller.quit())
next_button = Button(self, text="Next",
command=lambda: controller.show_frame("PageTwo"))
add_button = Button(self, text='Add',
command=add_compare)
quit_button.place(relx=0.98, rely=0.98, anchor=SE)
next_button.place(relx=0.76, rely=0.98, anchor=SE)
add_button.place(relx=0.661, rely=0.98, anchor=SE)
class PageTwo(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.controller = controller
def button():
label = Label(self, text=list_1)
label.pack()
quit_button = Button(self, text="Quit Program",
command=lambda: controller.quit())
back_button = Button(self, text="Back",
command=lambda: controller.show_frame("PageOne"))
show_button = Button(self, text='Show options', command=button)
show_button.pack()
back_button.place(relx=0.76, rely=0.98, anchor=SE)
quit_button.place(relx=0.98, rely=0.98, anchor=SE)
if __name__ == "__main__":
root = Validation_Tool()
root.geometry('400x300+430+250')
root.title("Validation Tool")
root.mainloop()
I am aware similar questions have been answered, but I have read them thoroughly and cannot find a solution for myself.
After the BMR_method is done, and either the if, elif, or else options has completed, I want it to automatically load a new class/frame: work . But I cannot figure out how to do this. I tried adding different variations of self.show_frame(work), also tried adding parent/controller parameters to the function but it will either tell me I am missing positional arguments or that the show_frame method doesn't exist. Please help.
import tkinter as tk
from decimal import Decimal
import time
LARGE_FONT = ("Verdana", 12)
def gender():
if var1.get() and var2.get():
print('Please only tick one box')
var1.set(0)
var2.set(0)
elif var1.get():
print('Male')
bmr_male()
elif var2.get():
print('Female')
bmr_female()
else:
print('Please tick male or female')
class theog(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
controller = 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, work):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_frame(StartPage)
def show_frame(self, controller):
frame = self.frames[controller]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Start Page", width = 60)
label.pack()
button = tk.Button(self, text="Begin!",
command=lambda: controller.show_frame(BMR))
button.pack()
class BMR(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="BMR Calculator", width = 20)
label.grid(column=0, row=0, sticky='W')
label_height = tk.Label(self, text="Height (CM)")
label_height.grid(column=3, row=0, sticky='E')
label_weight = tk.Label(self, text="Weight (KG)")
label_weight.grid(column=3, row=1, sticky='E')
label_age = tk.Label(self, text="Age")
label_age.grid(column=3, row=2, sticky='E')
self.text_height = tk.Entry(self, width=20, bg="white")
self.text_height.grid(row=0, column=4, sticky='W')
self.text_weight = tk.Entry(self, width=20, bg="white")
self.text_weight.grid(row=1, column=4, sticky='W')
self.text_age = tk.Entry(self, width=20, bg="white")
self.text_age.grid(row=2, column=4, sticky='W')
self.resultvar = tk.StringVar()
self.result = tk.Label(self, textvariable=self.resultvar)
self.result.grid(row=3, column=1)
self.var1 = tk.StringVar()
self.var1.set(None)
tk.Radiobutton(self, text="Male", bg='white', value='male', variable=self.var1).grid(row=0, column=1, sticky='S')
tk.Radiobutton(self, text="Female", bg='white', value='female', variable=self.var1).grid(row=1, column=1, sticky='S')
tk.Button(self, text="Submit!", width=6, command=self.bmr_method).grid(row=3, column=0, sticky='W')
def bmr_method(self, Entry=None):
if self.text_height.get() and self.text_weight.get() and self.text_age.get() and self.var1.get() == 'male':
bh = float(self.text_height.get()) * 5.0033
bw = float(self.text_weight.get()) * 13.7516
ba = float(self.text_age.get()) * 6.7550
bmr = float(66.4730 + bh + bw - ba)
self.resultvar.set('Your BMR is: ' + str(bmr))
elif self.text_height.get() and self.text_weight.get() and self.text_age.get() and self.var1.get() == 'female':
bh = float(self.text_height.get()) * 1.8496
bw = float(self.text_weight.get()) * 9.5634
ba = float(self.text_age.get()) * 4.6756
bmr = float(655.095 + bh + bw - ba).round(1)
self.resultvar.set('Your BMR is:' + str(bmr) +'\n press continue to find out \n your maintenance calories')
else:
'Please ensure all information has been entered and click again'
self.resultvar.set('Please ensure all \n information has been \n entered and click again')
self.controller.show_frame(work) #I WANT TO OPEN THE CLASS BELOW AFTER THIS METHOD HAS FINISHED
class work(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
controller = self
root = theog()
root.mainloop()
First, your class needs accept and save a reference to the controller so that you can access it later:
class BMR(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
...
Then, you simply need to call the controller method show_frame:
self.controller.switch_frame(work)
With the if-statement that I have put in, it would only display the lose statement even if it is correct.
I'm not sure if the way I wrote the statement is correct.
I'm trying to make it that when pressing start both labels would show a number between 1 to 21.
Also, if it's possible, I want to make it that when the hit button is pressed, a number would be added to the label. For example, pressing hit would add 10 + 5, then display the total.
LOCATED IN CLASS TTY:
import tkinter as tk
k = 10
Q = 10
J = 10
A = 11 or 1
class WINDOW(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Memory") #sets the window title
container = tk.Frame(self)#Name of frame to refer to
container.pack(side="top", fill="both", expand=True)#size of window
container.grid_rowconfigure(0, weight=4)#size of window
container.grid_columnconfigure(0, weight=4)
self.frames = {}
for F in (MainMenu, tty):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("MainMenu")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class MainMenu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = 'white')
label = tk.Label(self, text="Memory",font=(15),
borderwidth=5, relief="solid")
label.pack(side="top", fill="y", pady=15, padx=270)
label.pack(fill="both")
button1 = tk.Button(self, text="Start", relief="solid",
borderwidth=5,width=30,
font=(17),command=lambda:
controller.show_frame("tty"))
button1.pack()
button3 = tk.Button(self,
text="Quit",relief="solid",borderwidth=4,width=30,font=(17),command = quit)
button3.place(x="420", y ="50")
button3.pack()
class tty(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = "white")
def win():
if score > deal:
tts = tk.Label(self, text="win", font=(20))
tts.pack()
else:
lose = tk.Label(self, text="lose", font=(10))
lose.pack() #The if statement
deal = tk.Label(self, text="18", font=(18))
deal.pack(side="top", fill="y", pady=15, padx=270)
score = tk.Label(self, text="19", font=(18))
score.pack()
f = tk.Frame(self)
button1 = tk.Button(f,borderwidth=5, text="stand", font=(18),command =
lambda: win())#This is the button that i want to display the label
button1.grid(row=0,column=0)
button2 = tk.Button(f, text="Hit",borderwidth=5, font=(18))
button2.grid(row=0,column=1)
f.pack(side="bottom")
button3 = tk.Button(self, text="Quit", font=(18))
button3.pack(side="right", pady=50)
if __name__ == "__main__":
app = WINDOW()
app.geometry("800x400")
app.mainloop()
if score > deal: is comparing two tkinter label objects rather than the value of score and deal. Try getting the value of the labels and converting them to integers before doing the comparision.
if int(score['text']) > int(deal['text']):
To help with your other questions.
To chose a random number between 1 and 21, use the randint function contained inside python's random module (see code below). I've added a new randomise function which will be called after the page is created to randomly select a value for deal and score.
With the hit button, i've added a new function hit which will take the current score, and add another random value to it.
import tkinter as tk
from random import randint
k = 10
Q = 10
J = 10
A = 11 or 1
class WINDOW(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Memory") #sets the window title
container = tk.Frame(self)#Name of frame to refer to
container.pack(side="top", fill="both", expand=True)#size of window
container.grid_rowconfigure(0, weight=4)#size of window
container.grid_columnconfigure(0, weight=4)
self.frames = {}
for F in (MainMenu, tty):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("MainMenu")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class MainMenu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = 'white')
label = tk.Label(self, text="Memory",font=(15),
borderwidth=5, relief="solid")
label.pack(side="top", fill="y", pady=15, padx=270)
label.pack(fill="both")
button1 = tk.Button(self, text="Start", relief="solid",
borderwidth=5,width=30,
font=(17),command=lambda:
controller.show_frame("tty"))
button1.pack()
button3 = tk.Button(self,
text="Quit",relief="solid",borderwidth=4,width=30,font=(17),command = quit)
button3.place(x="420", y ="50")
button3.pack()
class tty(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(background = "white")
self.deal = tk.Label(self, text="18", font=(18))
self.deal.pack(side="top", fill="y", pady=15, padx=270)
self.score = tk.Label(self, text="19", font=(18))
self.score.pack()
f = tk.Frame(self)
button1 = tk.Button(f,borderwidth=5, text="stand", font=(18),command = self.win)#This is the button that i want to display the label
button1.grid(row=0,column=0)
button2 = tk.Button(f, text="Hit",borderwidth=5, font=(18),command = self.hit)
button2.grid(row=0,column=1)
f.pack(side="bottom")
button3 = tk.Button(self, text="Quit", font=(18))
button3.pack(side="right", pady=50)
self.randomise()
def randomise(self):
self.deal['text'] = str(randint(1,21))
self.score['text'] = str(randint(1,21))
def hit(self):
current_score = int(self.score['text'])
new_score = current_score + randint(1,21)
self.score['text'] = str(new_score)
def win(self):
if int(self.score['text']) > int(self.deal['text']):
tts = tk.Label(self, text="win", font=(20))
tts.pack()
else:
lose = tk.Label(self, text="lose", font=(10))
lose.pack() #The if statement
if __name__ == "__main__":
app = WINDOW()
app.geometry("800x400")
app.mainloop()
I want to create a widget outside his frame, but I don't know what's his master.
this is the structure.
first I created the class of the root. and then 3 classes of frames.
inside the class of the root I put a function. inside the function I created a text widget that should be located in the first one of the 3 frames
I really don't get what I should write as the master of my text widget to locate it in the first frame.
since I am a beginner if you have any advice I'd really appreciate.
thanks for attention here's the code
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import datetime
LARGE_FONT = ("VERDANA", 12)
#user's information manager(classes and method)
class person:
def __init__(self, name, birthday, sex):
self.name = name
self.birthday = birthday
self.sex = sex
def age(self, name, birthday):
user = person(name, birthday, "male")
today = datetime.date.today()
print (today.year - self.birthday.year)
#main windows
class deathCalculatorapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "age calculator app")
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):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
# all methods here
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
def calculate(self, name, birthday):
user = person(name, birthday, "male")
text_answer = tk.Text(master = , height=3, width=30)
text_answer.grid(column=1, row=9)
answear_text = ("{name} is {age} years old".format(name=name_entry.get(), age=calculate()))
text_answer.insert(tk.END, answear_text)
print (user.age()
#all of the frames
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
#Labels
label = ttk.Label(self, text="deathcalculatorapp", font=LARGE_FONT)
label.grid(column=1, row=0)
first_label = ttk.Label(self, text = "insert your data")
name_label= tk.Label(self, text = "name", bg="lightblue")
year_label = tk.Label(self, text="year", bg ="lightblue", padx=9)
month_label = tk.Label(self, text= "month", bg = "lightblue", padx=3)
day_label = tk.Label(self, text ="day", bg= "lightblue", padx=11)
first_label.grid(column=1, row=3)
name_label.grid(column=0, row=4)
year_label.grid(column=0, row =5)
month_label.grid(column=0, row =6)
day_label.grid(column=0, row = 7)
#Entries
name_entry = tk.Entry(self, text = "", bg = "lightblue")
year_entry = tk.Entry(self,text = "", bg = "lightblue")
month_entry = tk.Entry(self, text = "", bg= "lightblue")
day_entry = tk.Entry(self, text= "", bg = "lightblue")
name_entry.grid(column=1, row=4)
year_entry.grid(column=1,row=5)
month_entry.grid(column=1, row= 6)
day_entry.grid(column=1, row=7)
#Radiobutton about sex
sexdatum = tk.IntVar()
female= ttk.Radiobutton(self, text="female",variable= sexdatum, value="female")
male=ttk.Radiobutton(self, text="male", variable= sexdatum, value="male")
female.grid(column=2, row=4)
male.grid(column=2, row=5)
#Buttons
calculate_button = ttk.Button(self, text="calculate your lifespawn",
command=lambda: controller.age(name_entry.get(),datetime.date(int(year_entry.get()),int(month_entry.get()),int(day_entry.get()))))
calculate_button.grid(column=1, row=8)
button1 = ttk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = ttk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.grid(column=0, row=0)
button2.grid(column=0, row=1)
#text
#image
image = Image.open(r"/"
r"Users/tommasomasaracchio/Documents/pythonfolder/kushina4.jpg")
image.thumbnail((500,300), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image)
Photo_label= ttk.Label(self, image=photo)
Photo_label.image = photo
Photo_label.grid(row= 2, column = 1)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = ttk.Label(self, text="This is page 1", font=LARGE_FONT)
label.grid(column=0, row=0)
button = ttk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.grid(column=0, row=0)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = ttk.Label(self, text="This is page 2", font=LARGE_FONT)
label.grid(column=0, row=0)
button = ttk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.grid(column=0, row=0)
if __name__ == "__main__":
app = deathCalculatorapp()
app.mainloop()
It should be master = self.frames['StartPage'].