动态启用和禁用文本框 Python Tkinter

Dynamically enable and disable textbox Python Tkinter

我正在尝试实现以下行为: 相互排斥的文本框(条目标签),遵循

等规则

我的想法是在 'Entry' 标签的 'command' 属性上有一个 'check' 函数,这样当编辑每个文本框时,代码会检查所有指定的 'cause' 个文本框,如果满足某些条件,则禁用一组 'effect' 个文本框。

我相信我也必须转发声明所有的Entry标签,然后声明功能,然后配置Entry标签具有此功能,然后将它们打包到屏幕上。

有更好的方法吗?或者至少是一种避免前向声明要求的方法?

谢谢,欢迎索取更多信息!

编辑: 这是一个示例实现

entry1 = tk.Entry (window) 

entry2 = tk.Entry (window) 

def shut_x():
    if entry1.get() != "":
        entry2.configure(state="disabled")
    else:
        entry2.configure(state="normal")

entry1.configure(command=shut_x())

canvas1.create_window(650, 140, window=entry1)
canvas1.create_window(650, 340, window=entry2)

尝试这样的事情:

import tkinter as tk

def shut_x(*args):
    if entry1.get() != "":
        entry2.config(state="disabled")
    else:
        entry2.config(state="normal")

root = tk.Tk()

tk_variable = tk.StringVar(root)
tk_variable.trace("w", shut_x)

entry1 = tk.Entry(root, textvariable=tk_variable)
entry1.pack()

entry2 = tk.Entry(root)
entry2.pack()

root.mainloop()

这将创建一个 StringVar 变量并将其附加到 entry1。它还跟踪该变量,回调函数为 shut_x.

对于您请求的 3 个条目(用户只能写入其中的 2 个条目):

import tkinter as tk

def shut_x(*args):
    number_of_entries_with_text = 0
    number_of_entries_with_text += entry1.get() != ""
    number_of_entries_with_text += entry2.get() != ""
    number_of_entries_with_text += entry3.get() != ""
    # Check if some how you managed to insert text in all 3 of the entries:
    # It should never happen
    assert number_of_entries_with_text <= 2, "An internal error"
    if number_of_entries_with_text == 2:
        if entry1.get() == "":
            entry1.config(state="disabled")
        elif entry2.get() == "":
            entry2.config(state="disabled")
        elif entry3.get() == "":
            entry3.config(state="disabled")
    elif number_of_entries_with_text < 2:
        if entry1.get() == "":
            entry1.config(state="normal")
        if entry2.get() == "":
            entry2.config(state="normal")
        if entry3.get() == "":
            entry3.config(state="normal")

root = tk.Tk()

tk_variable_entry1 = tk.StringVar(root)
tk_variable_entry1.trace("w", shut_x)

tk_variable_entry2 = tk.StringVar(root)
tk_variable_entry2.trace("w", shut_x)

tk_variable_entry3 = tk.StringVar(root)
tk_variable_entry3.trace("w", shut_x)

entry1 = tk.Entry(root, textvariable=tk_variable_entry1)
entry1.pack()

entry2 = tk.Entry(root, textvariable=tk_variable_entry2)
entry2.pack()

entry3 = tk.Entry(root, textvariable=tk_variable_entry3)
entry3.pack()

root.mainloop()