如何通过选中复选框来锁定文本小部件



我是编程和Tkinter的新手。我想在按下复选框时DISABLED文本框,在未勾选复选框时打开它NORMAL。这是我的代码:

from tkinter import *
root = Tk()
def lock_fields():
if check == True:
data.configure(state=DISABLED)
if check == False:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check, 
onvalue=True, offvalue=False, command=lambda: lock_fields())
open_for_edit.pack()
check = check.get()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()

由于某种原因,当检查变量进入lock_fields函数时,它似乎总是False。我尝试将check参数传递给该方法。

您非常接近,唯一的问题是check.get()行必须在函数中。此外,您不需要lambda。试试这个:

from tkinter import *
root = Tk()
def lock_fields():
if check.get():
data.configure(state=DISABLED)
else:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check, onvalue=True, offvalue=False, command=lock_fields)
open_for_edit.pack()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()

最新更新