有没有办法使tkinter帧变灰(禁用)?

2024-10-03 00:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在tkinter中创建一个有两个框架的图形用户界面,并使底部框架变灰,直到发生某个事件。

下面是一些示例代码:

from tkinter import *
from tkinter import ttk

def enable():
    frame2.state(statespec='enabled') #Causes error

root = Tk()

#Creates top frame
frame1 = ttk.LabelFrame(root, padding=(10,10,10,10))
frame1.grid(column=0, row=0, padx=10, pady=10)

button2 = ttk.Button(frame1, text="This enables bottom frame", command=enable)
button2.pack()

#Creates bottom frame
frame2 = ttk.LabelFrame(root, padding=(10,10,10,10))
frame2.grid(column=0, row=1, padx=10, pady=10)
frame2.state(statespec='disabled') #Causes error

entry = ttk.Entry(frame2)
entry.pack()

button2 = ttk.Button(frame2, text="button")
button2.pack()

root.mainloop()

在不必单独将frame2的所有小部件灰显的情况下,这样做是否可行?

我正在使用Tkinter8.5和Python3.3。


Tags: fromimport框架tkinterenablerootframepack
1条回答
网友
1楼 · 发布于 2024-10-03 00:24:15

不知道它有多优雅,但我通过添加

for child in frame2.winfo_children():
    child.configure(state='disable')

它循环并禁用frame2的每个子级,并通过改变enable()来本质上用

def enable(childList):
    for child in childList:
        child.configure(state='enable')

此外,我删除了frame2.state(statespec='disabled'),因为这不符合我的需要,而且还会抛出一个错误。

下面是完整的代码:

from tkinter import *
from tkinter import ttk

def enable(childList):
    for child in childList:
        child.configure(state='enable')

root = Tk()

#Creates top frame
frame1 = ttk.LabelFrame(root, padding=(10,10,10,10))
frame1.grid(column=0, row=0, padx=10, pady=10)

button2 = ttk.Button(frame1, text="This enables bottom frame", 
                     command=lambda: enable(frame2.winfo_children()))
button2.pack()

#Creates bottom frame
frame2 = ttk.LabelFrame(root, padding=(10,10,10,10))
frame2.grid(column=0, row=1, padx=10, pady=10)

entry = ttk.Entry(frame2)
entry.pack()

button2 = ttk.Button(frame2, text="button")
button2.pack()

for child in frame2.winfo_children():
    child.configure(state='disable')

root.mainloop()

相关问题 更多 >