displaying information on another frame? (tkinter python) - python

so there is this stackoverflow question:
Switch between two frames in tkinter
Which looks like a beautiful basis for building an application. But what if on startPage i want to have multiply buttons, and display the appropriate data on PageOne? Here is my attempt:
import tkinter as tk
from functools import partial
characters = {"character1": "abc", "character2": "def", "character3": "ghi", "character4": "jkl", "character5": "mnp", "character6": "qrs" }
class AdventureGame:
''' controller for managiging frames '''
def __init__(self, master):
self.master = master
self.frames = {}
for F in (StartGame,ShowCharacters,CharacterDetail):
frame = F(parent=master, controller=self)
self.frames[F.__name__] = frame
frame.grid(row=0, column=0, sticky="nsew")
''' rais the first frame '''
self.raise_frame("StartGame")
def raise_frame(self,page_name):
''' raise a frame '''
frame = self.frames[page_name]
frame.tkraise()
def lower_frame(self,page_name):
''' lower a frame '''
frame = self.frames[page_name]
frame.lower()
class StartGame(tk.Frame):
''' introduction screen of the game '''
def __init__(self, parent, controller):
super(StartGame,self).__init__(parent)
self.controller = controller
''' introduction text '''
tk.Label(self, text="welcome to this game").grid()
tk.Button(self, text="next", command=lambda: controller.raise_frame("ShowCharacters")).grid()
class ShowCharacters(tk.Frame):
''' main frame, overview of all pokemon '''
def __init__(self, parent, controller):
super(ShowCharacters,self).__init__(parent)
self.controller = controller
for row, character in enumerate(characters):
name_label = tk.Label(self, text=characters[character])
name_label.grid(row=row,column=0)
info_button = tk.Button(self, text="view info", command=partial(self.switch,character))
info_button.grid(row=row,column=1)
def switch(self, character):
test = self.controller.raise_frame("CharacterDetail")
class CharacterDetail(tk.Frame):
''' detail view of pokemon '''
def __init__(self, parent, controller):
super(CharacterDetail,self).__init__(parent)
self.controller = controller
tk.Button(self, text="back", command=lambda: controller.lower_frame("CharacterDetail")).grid()
# somehow display characters name here
def showdetail(self):
tk.Label(self, text="test").grid()
def main():
root = tk.Tk()
app = AdventureGame(root)
root.mainloop()
main()
It feels like the the key is in the controller, as explained here:
How to get variable data from a class
It just feels like i am missing something, does someone have an idea? Or am i thinking in the wrong direction all together?
If i try to show the detail:
def switch(self, character):
test = self.controller.raise_frame("CharacterDetail")
CharacterDetail.showdetail(self)
it shows up at the ShowCharacters frame rather then the CharacterDetail frame
I guess because self is the frame, which is self from ShowCharacters
I need to do something with the controller, but my mind just goes blank
So now i pass information to the controller:
import tkinter as tk
from functools import partial
characters = {"character1": "abc", "character2": "def", "character3": "ghi", "character4": "jkl", "character5": "mnp", "character6": "qrs" }
class AdventureGame:
''' controller for managiging frames '''
def __init__(self, master):
self.master = master
self.frames = {}
for F in (StartGame,ShowCharacters,CharacterDetail):
frame = F(parent=master, controller=self)
self.frames[F.__name__] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.app_data = {"test": "test"}
''' rais the first frame '''
self.raise_frame("StartGame")
def raise_frame(self,page_name):
''' raise a frame '''
frame = self.frames[page_name]
frame.tkraise()
def lower_frame(self,page_name):
''' lower a frame '''
frame = self.frames[page_name]
frame.lower()
class StartGame(tk.Frame):
''' introduction screen of the game '''
def __init__(self, parent, controller):
super(StartGame,self).__init__(parent)
self.controller = controller
''' introduction text '''
tk.Label(self, text="welcome to this game").grid()
tk.Button(self, text="next", command=lambda: controller.raise_frame("ShowCharacters")).grid()
class ShowCharacters(tk.Frame):
''' main frame, overview of all pokemon '''
def __init__(self, parent, controller):
super(ShowCharacters,self).__init__(parent)
self.controller = controller
for row, character in enumerate(characters):
name_label = tk.Label(self, text=characters[character])
name_label.grid(row=row,column=0)
info_button = tk.Button(self, text="view info", command=partial(self.switch,character))
info_button.grid(row=row,column=1)
def switch(self, character):
test = self.controller.raise_frame("CharacterDetail")
CharacterDetail.example(self)
class CharacterDetail(tk.Frame):
''' detail view of pokemon '''
def __init__(self, parent, controller):
super(CharacterDetail,self).__init__(parent)
self.controller = controller
tk.Button(self, text="back", command=lambda: controller.lower_frame("CharacterDetail")).grid()
def example(self):
tk.Label(self, text=self.controller.app_data["test"]).grid()
def main():
root = tk.Tk()
app = AdventureGame(root)
root.mainloop()
main()
the label is still on the wrong frame, how can i get access to the right self so i can add the label to the right frame?

As you call CharacterDetail.example(self) in function switch(...) of class ShowCharacters, self will be class ShowCharacters. Therefore the label created in function example(self) of class CharacterDetail will be in ShowCharacters frame.
Try:
return the raised frame in function raise_frame(...) of class AdventureGame:
def raise_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
return frame # return the raised frame
modify function switch(...) of class ShowCharacters:
def switch(self, character):
frame = self.controller.raise_frame("CharacterDetail")
frame.example()

Related

tkinter: Using same frame but having different command button?

Pardon me for my bad grammar or explanation, since I didn't know how to explain this properly.
I try to build some gui that could switch between frame, using script from this as base Switch between two frames in tkinter.
In this case, I will have a few frame that had similar design, but different function when the button is pressed. For example, I have 2 frames that have similar 2 entries and 1 button, but the button do different command (where at sub01 frame it will multiply and at sub02 frame will divide)
This is my code:
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid(row=1,columnspan=4,sticky='nsew')
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (sub01, sub02):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=1,sticky="nsew")
self.choices = {'sub01','sub02'}
self.tkvar = tk.StringVar()
self.tkvar.set('sub01')
self.popMenu = tk.OptionMenu(self,self.tkvar,*self.choices)
self.popMenu.grid(row=0)
self.show_frame()
self.button1 = tk.Button(self, text="Go to Layer",command=lambda: self.show_frame())
self.button1.grid(row=0, column=1)
def show_frame(self):
'''Show a frame for the given page name'''
page_name = self.tkvar.get()
frame = self.frames[page_name]
frame.tkraise()
class sub01(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This SubLayer 1")
label.grid(row=0)
self.entries=[]
i = 0
while i < 2:
self.entries.append(tk.Entry(self,width=10))
self.entries[i].grid(row=i+1,columnspan=2,sticky='we')
i += 1
self.btn = tk.Button(self,text="multiply", command=lambda : self.multiply())
self.btn.grid(row=i+1, columnspan=2,sticky='we')
def multiply(self):
pass
class sub02(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This SubLayer 2")
label.grid(row=0)
self.entries=[]
i = 0
while i < 2:
self.entries.append(tk.Entry(self,width=10))
self.entries[i].grid(row=i+1,columnspan=2,sticky='w')
i += 1
self.btn = tk.Button(self,text="divide",command=lambda : self.divide())
self.btn.grid(row=i+1, columnspan=2,sticky='we')
def divide(self):
pass
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
This code itself works, but when I need to create more of these frames, it becomes inconvenient. How could I make this code simpler? Like having that similar frame as a class, and the button as other class that do differ behaviour depend of the layer shown.
Thank you in advance
The canonical way to do this sort of thing is to create a class hierarchy for your Page classes and put common functionality in the base classes and derive subclasses from them that specify the behavior that differs between them. Below is how you could do that with the sample code in your question.
Since the things that are different between them are:
The text displayed on the Label.
The text displayed on the Button.
The code in that's execute when the Button is clicked.
This means the derived classes only need to know what code to run in a generically named btn_func() method and what the text to displayed on the two widgets. The code below illustrates how to do that.
Note that I've changed the spelling of your class names to conform to the naming conventions describe in PEP 8 - Style Guide for Python Code.
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid(row=1,columnspan=4,sticky='nsew')
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Sub01, Sub02):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=1,sticky="nsew")
self.choices = {'Sub01','Sub02'}
self.tkvar = tk.StringVar()
self.tkvar.set('Sub01')
self.popMenu = tk.OptionMenu(self,self.tkvar,*self.choices)
self.popMenu.grid(row=0)
self.show_frame()
self.button1 = tk.Button(self, text="Go to Layer",command=lambda: self.show_frame())
self.button1.grid(row=0, column=1)
def show_frame(self):
'''Show a frame for the given page name'''
page_name = self.tkvar.get()
frame = self.frames[page_name]
frame.tkraise()
class BaseSubLayer(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text=self.lbl_text)
label.grid(row=0)
self.entries=[]
i = 0
while i < 2:
self.entries.append(tk.Entry(self,width=10))
self.entries[i].grid(row=i+1,columnspan=2,sticky='we')
i += 1
self.btn = tk.Button(self,text=self.btn_func_name, command=self.btn_func)
self.btn.grid(row=i+1, columnspan=2,sticky='we')
def btn_func(self):
raise NotImplementedError
class Sub01(BaseSubLayer):
lbl_text = 'This SubLayer 1'
btn_func_name = 'multiply'
def btn_func(self):
print('Running multiply() method.')
class Sub02(BaseSubLayer):
lbl_text = 'This SubLayer 2'
btn_func_name = 'divide'
def btn_func(self):
print('Running divide() method.')
if __name__ == "__main__":
app = SampleApp()
app.mainloop()

How to save shared data in tkinter for python?

I'm very new to the world of GUIs with Python and attempting to build my first one with multiple pages, but sharing a variable from an entry box is really throwing me through a loop. I understand there's probably a lot wrong with the code, but for now, I would really just like to better understand how to share the variables between the pages from the username entry box.
Here is the code that ties into this:(The page breaks are just where there is some unrelated code)
import tkinter as tk
from tkinter import Tk, Label, Button, StringVar
class Keep(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.shared_data ={
"email": tk.StringVar(),
"password": tk.StringVar()
}
# Skipping some code to get to the good stuff
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# LABELS, ENTRIES, AND BUTTONS
# page break
self.entry1 = tk.Entry(self, textvariable=self.controller.shared_data["email"])
entry2 = tk.Entry(self, show = '*')
button1 = tk.Button(text="Submit", command=lambda: [controller.show_frame("PageTwo"), self.retrieve()])
# page break
def retrieve(self):
self.email = self.controller.shared_data["email"].get()
self.controller.email = self.email
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.email = self.controller.shared_data["email"].get()
label1 = tk.Label(self, text="Welcome, {}".format(self.email))
if __name__ == "__main__":
keep = Keep()
keep.mainloop()
I know the retrieve function looks pretty funky and probably not at all correct, but I've been working on this specific problem for about a week now and it has lead me down some wild rabbit holes.
The end goal is for label1 of pageTwo to display, "Welcome, (insert e-mail entered in entry1 of startPage)".
I think my issue lies with pageTwo retrieving an empty string from shared_data, but I don't understand why that is.
Any help is super appreciated!
I guess problem is because frames are created in Keep.__init__, not when you run show_frame(), so PageTwo.__init__() is executed at start and text Welcome... is create at start - before you even see StartPage.
You should create empty label in __init__ and create text Welcome... in other method (ie. update_widgets()) which you will execute after show_frame() or event inside show_frame() if all classes will have update_widgets()>
Minimal working code:
import tkinter as tk
class Keep(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.shared_data ={
"email": tk.StringVar(),
"password": tk.StringVar()
}
self.frames = {
'StartPage': StartPage(self, self),
'PageTwo': PageTwo(self, self),
}
self.current_frame = None
self.show_frame('StartPage')
def show_frame(self, name):
if self.current_frame:
self.current_frame.forget()
self.current_frame = self.frames[name]
self.current_frame.pack()
self.current_frame.update_widgets() # <-- update data in widgets
class StartPage(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
self.entry1 = tk.Entry(self, textvariable=self.controller.shared_data["email"])
self.entry1.pack()
entry2 = tk.Entry(self, show='*')
entry2.pack()
button = tk.Button(self, text="Submit", command=lambda:controller.show_frame("PageTwo"))
button.pack()
def update_widgets(self):
pass
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
self.label = tk.Label(self, text="") # <-- create empty label
self.label.pack()
def update_widgets(self):
self.label["text"] = "Welcome, {}".format(self.controller.shared_data["email"].get()) # <-- update text in label
if __name__ == "__main__":
keep = Keep()
keep.mainloop()

Variables from other classes in Tkinter [duplicate]

This is a shortened example of a longer application where I have multiple pages of widgets collecting information input by the user. The MyApp instantiates each page as a class. In the example, PageTwo would like to print the value of the StringVar which stores the data from an Entry widget in PageOne.
How do I do that? Every attempt I've tried ends up with one exception or another.
from tkinter import *
from tkinter import ttk
class MyApp(Tk):
def __init__(self):
Tk.__init__(self)
container = ttk.Frame(self)
container.pack(side="top", fill="both", expand = True)
self.frames = {}
for F in (PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky = NSEW)
self.show_frame(PageOne)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class PageOne(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
ttk.Label(self, text='PageOne').grid(padx=(20,20), pady=(20,20))
self.make_widget(controller)
def make_widget(self, controller):
self.some_input = StringVar
self.some_entry = ttk.Entry(self, textvariable=self.some_input, width=8)
self.some_entry.grid()
button1 = ttk.Button(self, text='Next Page',
command=lambda: controller.show_frame(PageTwo))
button1.grid()
class PageTwo(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
ttk.Label(self, text='PageTwo').grid(padx=(20,20), pady=(20,20))
button1 = ttk.Button(self, text='Previous Page',
command=lambda: controller.show_frame(PageOne))
button1.grid()
button2 = ttk.Button(self, text='press to print', command=self.print_it)
button2.grid()
def print_it(self):
print ('The value stored in StartPage some_entry = ')#What do I put here
#to print the value of some_input from PageOne
app = MyApp()
app.title('Multi-Page Test App')
app.mainloop()
Leveraging your controller
Given that you already have the concept of a controller in place (even though you aren't using it), you can use it to communicate between pages. The first step is to save a reference to the controller in each page:
class PageOne(ttk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...
class PageTwo(ttk.Frame):
def __init__(self, parent, controller):
self.controller = controller
...
Next, add a method to the controller which will return a page when given the class name or some other identifying attribute. In your case, since your pages don't have any internal name, you can just use the class name:
class MyApp(Tk):
...
def get_page(self, classname):
'''Returns an instance of a page given it's class name as a string'''
for page in self.frames.values():
if str(page.__class__.__name__) == classname:
return page
return None
note: the above implementation is based on the code in the question. The code in the question has it's origin in another answer here on stackoverflow. This code differs from the original code slightly in how it manages the pages in the controller. This uses the class reference as a key, the original answer uses the class name.
With that in place, any page can get a reference to any other page by calling that function. Then, with a reference to the page, you can access the public members of that page:
class PageTwo(ttk.Frame):
...
def print_it(self):
page_one = self.controller.get_page("PageOne")
value = page_one.some_entry.get()
print ('The value stored in StartPage some_entry = %s' % value)
Storing data in the controller
Directly accessing one page from another is not the only solution. The downside is that your pages are tightly coupled. It would be hard to make a change in one page without having to also make a corresponding change in one or more other classes.
If your pages all are designed to work together to define a single set of data, it might be wise to have that data stored in the controller, so that any given page does not need to know the internal design of the other pages. The pages are free to implement the widgets however they want, without worrying about which other pages might access those widgets.
You could, for example, have a dictionary (or database) in the controller, and each page is responsible for updating that dictionary with it's subset of data. Then, at any time you can just ask the controller for the data. In effect, the page is signing a contract, promising to keep it's subset of the global data up to date with what is in the GUI. As long as you maintain the contract, you can do whatever you want in the implementation of the page.
To do that, the controller would create the data structure before creating the pages. Since we're using tkinter, that data structure could be made up of instances of StringVar or any of the other *Var classes. It doesn't have to be, but it's convenient and easy in this simple example:
class MyApp(Tk):
def __init__(self):
...
self.app_data = {"name": StringVar(),
"address": StringVar(),
...
}
Next, you modify each page to reference the controller when creating the widgets:
class PageOne(ttk.Frame):
def __init__(self, parent, controller):
self.controller=controller
...
self.some_entry = ttk.Entry(self,
textvariable=self.controller.app_data["name"], ...)
Finally, you then access the data from the controller rather than from the page. You can throw away get_page, and print the value like this:
def print_it(self):
value = self.controller.app_data["address"].get()
...
I faced a challenge in knowing where to place the print_it function.
i added the following to make it work though I don't really understand why they are used.
def show_frame(self,page_name):
...
frame.update()
frame.event_generate("<<show_frame>>")
and added the show_frame.bind
class PageTwo(tk.Frame):
def __init__(....):
....
self.bind("<<show_frame>>", self.print_it)
...
def print_it(self,event):
...
Without the above additions, when the mainloop is executed,
Page_Two[frame[print_it()]]
the print_it function executes before PageTwo is made Visible.
try:
import tkinter as tk # python3
from tkinter import font as tkfont
except ImportError:
import Tkinter as tk #python2
import tkFont as tkfont
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family="Helvetica", size=18, weight="bold", slant="italic")
# data Dictionary
self.app_data = {"name": tk.StringVar(),
"address": tk.StringVar()}
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others.
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")
def show_frame(self, page_name):
''' Show a frame for the given page name '''
frame = self.frames[page_name]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="this is the start page", font=self.controller.title_font)
label.pack(side="top", fill="x", pady=10)
# Update the Name value only
self.entry1 = tk.Entry(self,text="Entry", textvariable=self.controller.app_data["name"])
self.entry1.pack()
button1 = tk.Button(self, text="go to page one", command = lambda: self.controller.show_frame("PageOne")).pack()
button2 = tk.Button(self, text="Go to page Two", command = lambda: self.controller.show_frame("PageTwo")).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", font=self.controller.title_font)
label.pack(side="top", fill="x", pady=10)
# Update the Address value only
self.entry1 = tk.Entry(self,text="Entry", textvariable=self.controller.app_data["address"])
self.entry1.pack()
button = tk.Button(self, text="Go to the start page", command=lambda: self.controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# Bind the print_it() function to this Frame so that when the Frame becomes visible print_it() is called.
self.bind("<<show_frame>>", self.print_it)
label = tk.Label(self, text="This is page 2", font=self.controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: self.controller.show_frame("StartPage"))
button.pack()
def print_it(self,event):
StartPage_value = self.controller.app_data["name"].get()
print(f"The value set from StartPage is {StartPage_value}")
PageOne_value= self.controller.app_data["address"].get()
print(f"The value set from StartPage is {PageOne_value}")
if __name__ == "__main__":
app = SampleApp()
app.mainloop()

Passing a variable to frame

I am creating a password manager software. The passwords are stored in different categories. When I click on the category it should open a ViewPasswordsInsideCategory page.
I am unable to pass the category name to the ViewPasswordsInsideCategory page.
Please help! I am new to Python and cant solve this issue.
I tried to pass an argument when I can showframe function but I couldn't achieve the goal.
class PasswordPage(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
self.shared_data = {
"category": tk.StringVar(),
"password": tk.StringVar()}
self.passwordScreen = Frame(self)
self.passwordScreen.pack(fill="both", expand=True)
self.passwordScreen.columnconfigure(0, weight=1)
self.passwordScreen.rowconfigure(0, weight=1)
self.frames = {}
for F in (PasswordCategoryPage,ViewPasswords_InCategory,CreateNewPassword,ViewPassword,ModifyPassword):
page_name = F.__name__
frame = F(parent=self.passwordScreen, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("PasswordCategoryPage")
def show_frame(self, page_name, arg=None):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class PasswordCategoryPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# passwords categories content
self.labels = []
self.dict = {'Home': 'Blue', 'Work': 'Red', 'School': 'Yellow', "Technical": 'Pink', "Office": 'Orange'}
self.button = []
j = 0
for key, value in self.dict.items():
self.name = key
self.key = Label(self.pass_page_container,text=self.name,bg=value)
# Add the Label to the list
self.labels.append(key)
self.key.grid(row=j, column=0, sticky=(N, S, E, W))
self.key.bind("<Double-Button-1>", self.showPasswordPage)
j = j + 1
def showPasswordPage(self,event):
#here need to pass the label that was clicked to the ViewPasswords_InCategory page
self.controller.show_frame("ViewPasswords_InCategory")
class ViewPasswords_InCategory(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
#here need the name of the category selected to extract data from database
# home banner
home_label = Label(self, text=here need the name of the category, bg="blue", width=200, height=3, fg='white')
home_label.pack(side=TOP, expand=False)
The simply way is to add a new function in class ViewPasswords_InCategory to update the banner. Then whenever you switch to the page, call the new function. My proposed changes are:
1) return the frame that is raised in function PasswordPage.show_frame(...):
class PasswordPage(Page):
...
def show_frame(self, page_name, arg=None):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
return frame # return the raised frame
2) add new function, for example set_category(...) inside class ViewPasswords_InCategory to update its banner:
class ViewPasswords_InCategory(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# home banner
self.home_label = Label(self, text='', bg="blue", width=200, height=3, fg='white') # changed to instance variable
self.home_label.pack(side=TOP, expand=False)
# new function to update banner
def set_category(self, category):
self.home_label['text'] = category
3) update PasswordCategoryPage.showPasswordPage(...) to call the new fucntion:
class PasswordCategoryPage(tk.Frame):
...
def showPasswordPage(self,event):
#here need to pass the label that was clicked to the ViewPasswords_InCategory page
self.controller.show_frame("ViewPasswords_InCategory").set_category(event.widget['text'])

How do you change the variable in a function from a different class and call it back?

I am making a game with levels and in each level, I will need to be using different operators and/or different ranges. My problem is that I don't know how to change the variables in a function from a different class. I would like to do this so I don't need to copy and paste my code making it lengthy. I'd like to use self.Answer and self.strQuestion for mulitple scope.
The code below is just to make the classes functional.
from tkinter import *
import tkinter as tk
import random
from Tkinter import messagebox
class BattleMaths(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, levelone, leveltwo):
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)
lvl1_button = Button(self, text="LEVEL 1", command=lambda: controller.show_frame(levelone))
lvl1_button.place(relx=0.5, rely=0.5, anchor='center')
I want to put the questions def into class leveltwo while changing it to self.Answer = int(numOne) * int(numTwo) and self.strQuestion = "{} x {}".format(str(numOne), str(numTwo))
class levelone(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def widgets(self):
#widgets here
def question(self):
self.UserAnswer = ''
numOne = random.randrange(1,10)
numTwo = random.randrange(1,10)
self.Answer = int(numOne) + int(numTwo) #change this
self.strQuestion = "{} + {}".format(str(numOne), str(numTwo)) #and change this
def answer(self):
#answer checker
class leveltwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#question def here
root = BattleMaths()
root.title("Battle Maths")
root.geometry("400x250")
root.resizable(0,0)
root.mainloop()
Create the variables you want in the main class (BattleMaths), then you can alter them in the child classes via controller.my_variable.
Example: self.Answer created in BattleMaths and accessed in levelone via controller.Answer

Categories

Resources