GreenSaber
GreenSaber

Reputation: 1148

Tkinter: Using the same frame to display data based on user input

Is there a way to use the same frame to display two different layouts of data based on user input? For example, if I have a button to make a variable either true or false, is there a way to show different text, labels, and data on the same frame based on if that variable is true or false? Something like this:

self.frame1 = Frame(root)
self.frame1.pack()

def page1(self):
    self.text1 = Label(self.frame1, text='Text 1')
    self.text1.pack()

def page2(self):
    self.text2 = Label(self.frame1, text='Text 2')
    self.text2.pack()

self.page1_or_page2 = True

if self.page1_or_page2 == True:
    page1(self)
else:
    page2(self)

Also, is overlapping data on a frame the best way to achieve something like this? Thanks!

Upvotes: 0

Views: 1130

Answers (1)

j_4321
j_4321

Reputation: 16169

You can do it by associating a command to a Checkbutton that will change the widgets displayed in the frame. You can use pack_forget to remove the widgets displayed in the frame before packing new ones.

Here is an example:

import tkinter as tk

def toggle_details():
    if variable.get():
        text1.pack_forget()
        text2.pack()
    else:
        text2.pack_forget()
        text1.pack()

root = tk.Tk()

frame = tk.Frame(root)
text1 = tk.Label(frame, text='short text')
text2 = tk.Label(frame, text='short text\n------\nwith details below')

variable = tk.BooleanVar(root)
button = tk.Checkbutton(root, text='Show details', command=toggle_details, variable=variable)

text1.pack()
frame.pack()
button.pack(side='bottom')

root.mainloop()

Upvotes: 1

Related Questions