使小部件消失在一帧中

问题描述 投票:0回答:1
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()

我需要帮助弄清楚如何使小部件消失。基本上,当按下状态时,城市选项就会弹出。但是-如果选择其他状态,我希望此类选项消失。现在,当按下德克萨斯州时,将弹出Houston / Dallas,但如果选择了NJ,它仍然停留在屏幕上。如果选择了另一个州,我如何销毁城市选项?

python tkinter widget
1个回答
0
投票

我还将把您的州/城市从if-else中移出,只需要为每个州调用一个函数的按钮,就可以通过这种方式轻松添加状态(至少在我看来,这更容易)。在每个状态回调的开始,我调用了clear框架。您还可以在clear函数中使用pack_forget()。我不确定哪一个都有好处,但是我通常使用destroy(),因为它较短,并且它不需要知道事物是通过grid()还是pack()进行的,我通常会忘记'_ '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()
© www.soinside.com 2019 - 2024. All rights reserved.