Python tkinter disable the button until all the fields are filled(Python tkinter 禁用按钮,直到所有字段都填满)
问题描述
假设我在 tkinter 中有 2 个条目小部件、1 个选项菜单(下拉列表)和 1 个按钮.在用户填充所有 3 个小部件之前,如何将按钮小部件状态设置为 DISABLED?这是我目前拥有的:
Let's say I have 2 entry widgets, 1 option menu(drop down list) and 1 button in tkinter. How can i set the button widget state to DISABLED until all 3 widgets are filled by the user?This is what i have currently:
import Tkinter as tk
root = tk.Tk()
entry1=tk.Entry(root,width=15).grid(row=1,column=1)
entry2=tk.Entry(root,width=15).grid(row=1,column=2)
choices=('a','b','c')
var=tk.StringVar(root)
option=tk.OptionMenu(root,var,*choices)
option.grid(row=1,column=3)
button=tk.Button(root,text="submit")
button.grid(row=1,column=4)
root.mainloop()
--编辑--
尝试过这种方式,但我认为这不是正确的方式.
Tried this way, but i don't think this is the correct way to do it.
import Tkinter as tk
root = tk.Tk()
def myfunction(event):
x=var.get()
y=entry1.get()
z=entry2.get()
print len(x),":",len(y),":",len(z)
if len(y)>0 and len(x)>0 and len(z)>0:
button.config(state='normal')
else:
button.config(state='disabled')
entry1=tk.Entry(root,width=15)
entry1.grid(row=1,column=1)
entry2=tk.Entry(root,width=15)
entry2.grid(row=1,column=2)
choices=('a','b','c')
var=tk.StringVar(root)
option=tk.OptionMenu(root,var,*choices)
option.grid(row=1,column=3)
button=tk.Button(root,text="submit")
button.grid(row=1,column=4)
root.bind("<Enter>", myfunction)
root.mainloop()
推荐答案
Tkinter 变量有一个叫trace
的方法来添加观察者,所以当值改变时会调用回调函数.我认为它比 root.bind("<Enter>", myfunction)
:
Tkinter variables have a method called trace
to add an observer, so the callback function is called when the value changes. I think it is much more efficient than root.bind("<Enter>", myfunction)
:
import Tkinter as tk
root = tk.Tk()
def myfunction(*args):
x = var.get()
y = stringvar1.get()
z = stringvar2.get()
if x and y and z:
button.config(state='normal')
else:
button.config(state='disabled')
stringvar1 = tk.StringVar(root)
stringvar2 = tk.StringVar(root)
var = tk.StringVar(root)
stringvar1.trace("w", myfunction)
stringvar2.trace("w", myfunction)
var.trace("w", myfunction)
entry1 = tk.Entry(root, width=15, textvariable=stringvar1)
entry1.grid(row=1,column=1)
entry2 = tk.Entry(root, width=15, textvariable=stringvar2)
entry2.grid(row=1,column=2)
choices = ('a','b','c')
option = tk.OptionMenu(root, var, *choices)
option.grid(row=1,column=3)
button = tk.Button(root,text="submit")
button.grid(row=1, column=4)
root.mainloop()
这篇关于Python tkinter 禁用按钮,直到所有字段都填满的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python tkinter 禁用按钮,直到所有字段都填满


基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01