在我每次打開新檔案時構建的 tkinter 應用程式(win10 python 3.8)中,我都會得到一個新串列,我將其分發到文本框(確定)、組合框(確定)等。當我打開第一個串列復選框時,回圈構建好的,下一個名為復選框的檔案不會改變。我無法更新復選框,我的意思是,洗掉以前的串列并插入另一個串列。在我習慣使用按鈕的示例中(在應用程式 askopenfilename 中),串列構建一個下面一個。我需要一個替換另一個。我相信我需要使用 grid.clear() 或 destroy,但如何使用?提前致謝。
from tkinter import *
root = Tk()
root.geometry('400x400')
my_friends = ['Donald', 'Daisy', 'Uncle Scrooge', 'Ze Carioca']
my_heroes = ['Captain America', 'Hulk', 'Spider Man', 'Black Widow',
'Wanda Maximoff', 'Vision', 'Winter Soldier']
what_list = ' '
def list_my_friends():
global what_list
what_list = my_friends
create_cbox()
def list_my_heroes():
global what_list
what_list = my_heroes
create_cbox()
def create_cbox():
for index, friend in enumerate(what_list):
current_var = tk.StringVar()
current_box = tk.Checkbutton(root, text= friend,
variable = current_var,
onvalue = friend,
offvalue = '')
current_box.pack()
button1= tk.Button(root, text = "my_friends",command=lambda:list_my_friends()).pack()
button2= tk.Button(root, text = "my_heroes",command=lambda:list_my_heroes()).pack()
root.mainloop()
uj5u.com熱心網友回復:
您可以將這些復選按鈕放在一個框架中,然后在填充新的復選按鈕之前洗掉舊的復選按鈕會更容易:
def create_cbox():
# remove existing checkbuttons
for w in container.winfo_children():
w.destroy()
# populate new checkbuttons
for friend in what_list:
current_var = tk.StringVar()
# use container as the parent
current_box = tk.Checkbutton(container, text=friend,
variable=current_var,
onvalue=friend,
offvalue='')
current_box.pack(anchor='w')
tk.Button(root, text="my_friends", command=list_my_friends).pack()
tk.Button(root, text="my_heroes", command=list_my_heroes).pack()
# frame to hold the checkbuttons
container = tk.Frame(root)
container.pack(padx=10, pady=10)
uj5u.com熱心網友回復:
我在課堂上作業時幾乎沒有調整:
class PageEight(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent) # parent is Frame
self.controller = controller
# to adequate to widgets outside the self.container_pg8:
self.rowspan_list = len(what_list)
#container:
self.container_pg8 = tk.Frame(self)
self.container_pg8.grid(row=2,
rowspan = self.rowspan_list,
column=1,)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315529.html
