Function to switch between two frames in tkinter

2024/10/5 7:36:42

I'm looking through the code at passing-functions-parameters-tkinter-using-lambda, and needed a tad more functionality inside his class PageOne(tk.Frame). Instead of using lambda commands below (as he did):

button1 = tk.Button(self, text="Back to Home",command=lambda: controller.show_frame(StartPage))`

I'd like to be able to create a function that had an if/then hierarchy inside of it... specifically to check if all other inputs on PageOne had been fulfilled first (which I then know how to do) before allowing a frame change.

If this can be done individually using lambda, even better. Can anyone help me out?


Update: Using Bryan's advice and reformatting for the original code he linked, I now have:

class App(tk.Tk):def __init__(self, *args, **kwargs):tk.Tk.__init__(self, *args, **kwargs)tk.Tk.wm_title(self, "APP") #window headingself.title_font = tkfont.Font(family='Helvetica', size=12) #options: weight="bold",slant="italic"container = tk.Frame(self) #container = stack of frames; one on top is visiblecontainer.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):page_name = F.__name__frame = F(parent=container, controller=self)self.frames[page_name] = frame #puts all pages in stacked orderframe.grid(row=0, column=0, sticky="nsew")self.show_frame("StartPage")def show_frame(self, page_name): #show a frame for the given page nameframe = self.frames[page_name]frame.tkraise()class StartPage(tk.Frame):def __init__(self, parent, controller):tk.Frame.__init__(self, parent)self.controller = controllerlabel = tk.Label(self, text="This is the start page", font=controller.title_font)label.pack(side="top", fill="x", pady=10)button1 = tk.Button(self, text="Go to Page One",command=lambda: controller.show_frame("PageOne"))button1.pack()button2.pack()class PageOne(tk.Frame):def __init__(self, parent, controller):tk.Frame.__init__(self, parent)self.controller = controller####FIX PART 1####self.next1 = tk.Button(self,text="Next",padx=18,highlightbackground="black", command=lambda: self.maybe_switch("PageTwo"))  self.next1.grid(row=10,column=1,sticky='E')####FIX PART 2####def maybe_switch(self, page_name):if ###SOMETHING###:self.controller.show_frame(page_name)if __name__ == "__main__":app = App()app.mainloop()
Answer

You shouldn't put any logic in a lambda. Just create a normal function that has any logic you want, and call it from the button. It's really no more complicated that that.

class SomePage(...):def __init__(...):...button1 = tk.Button(self, text="Back to Home", command=lambda: self.maybe_switch_page(StartPage))...def maybe_switch_page(self, destination_page):if ...:self.controller.show_frame(destination_page)else:...

If you want a more general purpose solution, move the logic to show_frame, and have it call a method on the current page to verify that it is OK to switch.

For example:

    class Controller(...):...def show_frame(self, destination):if self.current_page is None or self.current_page.ok_to_switch():# switch the pageelse:# don't switch the page

Then, it's just a matter of implementing ok_to_switch in every page class.

https://en.xdnf.cn/q/120001.html

Related Q&A

Get values from a tuple in a list in Python

x = Bookshop() x.orders = [ [1, ("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)], [2, ("5464", 9, 9.99), ("9744", 9, 44.95)], [3, ("5464&…

Last Digit of the Sum of Fibonacci Numbers

I am trying to find the last digit of sum of Fibonacci Series. I calculate the sum as F(n+2) - 1. The below code is working fine but it is slow for large numbers (e.g 99999). How can I optimize this?n…

Django websites not loading

I have two Django websites on one server using Apache with mod_wsgi on Windows 10. For some reason the Django websites dont load, however, I have a normal website that does. Ive had it work in the past…

list manipulation and recursion

I have a mansory-grid in a pdf-page. The grid is choosen randomly, so i do not know how much upright cells or cross cells I have to fill. In my list I have all images that I want to proceed, each marke…

Getting TypeError: int object is not callable

Getting TypeError: int object is not callable. What am i doing wrong as i just want to add 10 to the z variableprint ("Hello World")x=int(input("Enter X")) y=int(input("Enter Y…

How to create a loop from 1-9 and from a-z?

I currently use:for i in range(1,10):print iWhich prints the digits 1 to 9. But I want to add a-z to the mix. How can I combine them?

Need Python to accept upper and lower case input

I want my Python code to accept both uppercase and lowercase input.Ive tried casefold, but with no luck. Any help?advice ="" while advice !=("Yes"):print("Would you like some…

What is [1] , in sock.getsockname()[1]? [duplicate]

This question already has answers here:How to access List elements(5 answers)Closed 7 years ago.I was going through socket programming in Python and I saw this: sock.getsockname()[1] Can anyone please …

How to use sys.exit() if input is equal to specific number

I am looking to correct this code so that when the user inputs 99999 then the code stops running, im also looking to make it so that if the user input is 999 it sets the total to 0 import sysdef money_…

python about linking sublist with same number together

I need to group sublists with the same elements together For example:list1 =[[1, 0], [2, 1], [30, 32]]would link [1, 0] and [2, 1] together since they both contain 1 and those two would combine into [0…