Reputation: 87
import tkinter as tk
from tkinter import *
root= Tk()
root.title('Select State')
framey=Frame(root)
d_type = tk.StringVar()
d_type.set('1')
d1 = Radiobutton(root, variable=d_type, text="Texas", value="Texas",command=lambda: cities(root))
d1.pack()
d2 = Radiobutton(root, variable=d_type, text="NJ", value="NJ",command=lambda: cities(root))
d2.pack()
def cities(root):
texas= "Texas"
nj ="NJ"
state = d_type.get()
if state== texas:
f_band = tk.StringVar()
f_band.set('Dallas')
f1 = Radiobutton(framey, variable=f_band, text="Dallas", value="Dallas")
f1.pack()
f2 = Radiobutton(framey, variable=f_band, text="Houston", value="Houston")
f2.pack()
if state== nj:
f_band = tk.StringVar()
f_band.set('Newark')
f1 = Radiobutton(framey, variable=f_band, text="Newark", value="Newark")
f1.pack()
f2 = Radiobutton(framey, variable= f_band, text="Princeton", value="Princeton")
f2.pack()
framey.pack()
I need help figuring out how to make a widget disappear. Basically when a state is pressed, city options pop up. However- I want such options to disappear if another state is selected. Right now when Texas is pressed Houston/Dallas pops up, but still stays on the screen if NJ is selected. How do I destroy the city options from appearing if another state is selected?
Upvotes: 0
Views: 71
Reputation: 234
I would also take your state/city out of an if-else and just go with the button calling a function for each state, its easier to add states this way (at least in my mind its easier). At the start of each state callback, I have the frame clear called. you could also use pack_forget() in the clear function. I'm not sure of a benefit toward either one, but I typically use destroy() because its shorter, and it doesn't require knowing if things were grid()ed or pack()ed, and I normally forget the '_' in pack/grid_forget().
from tkinter import *
def clearF(fr):
frame = fr
for item in frame.winfo_children():
item.destroy()
#item.pack_forget()
#either destroy
def citiesTX():
clearF(framey)
f_band.set('Dallas')
f1 = Radiobutton(framey, variable=f_band, text="Dallas", value="Dallas")
f1.pack()
f2 = Radiobutton(framey, variable=f_band, text="Houston", value="Houston")
f2.pack()
def citiesNJ():
clearF(framey)
f_band.set('Newark')
f1 = Radiobutton(framey, variable=f_band, text="Newark", value="Newark")
f1.pack()
f2 = Radiobutton(framey, variable= f_band, text="Princeton", value="Princeton")
f2.pack()
root= Tk()
root.title('Select State')
framey=Frame(root)
d_type = StringVar()
f_band = StringVar()
d_type.set('0')
d1 = Radiobutton(root, variable=d_type, text="Texas", value="Texas",
command= citiesTX)
d1.pack()
d2 = Radiobutton(root, variable=d_type, text="NJ", value="NJ",
command= citiesNJ)
d2.pack()
framey.pack()
root.mainloop()
Upvotes: 1