【问题标题】:Tkinter how to lock Text widget by checking checkbox?Tkinter如何通过选中复选框来锁定文本小部件?
【发布时间】:2020-12-05 05:14:54
【问题描述】:

我是编程和 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。我尝试将检查参数传递给该方法。

【问题讨论】:

    标签: python tkinter checkbox boolean


    【解决方案1】:

    你已经很接近了,唯一的问题是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()
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多