[英]How can I disable a button in Python tkinter based on if there is text in the box or not?
I would like to ask, how can I change the state of a Button in Python Tkinter from DISABLED to NORMAL, based on if there is text in the entry box or not?请问,如何根据输入框中是否有文字,将Python Tkinter中的一个Button的state从DISABLED改成NORMAL?
I have copied this code and I am trying to modify it for practice.我已经复制了这段代码,并且正在尝试修改它以供练习。 Please feel free to run to make it simpler to understand my problem.请随时运行,以便更容易理解我的问题。
import tkinter as tk
from tkinter import *
base = Tk()
base.title("Lenny")
base.geometry("600x700")
base.resizable(width=FALSE, height=FALSE)
#Create Chat window
ChatLog = Text(base, bd=0, bg="white", height="8", width="50", font="Arial",)
ChatLog.config(state=DISABLED)
#Bind scrollbar to Chat window
scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
#Create Button to send message
SendButton = Button(base, font=("Segoe",12,'bold'), text="Send", width="12", height=5,
bd=0, bg="#C0C0C0", activebackground="#DCDCDC",fg='#000000',
command= send, state = NORMAL)
#Create the box to enter message
EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial")
#Place all components on the screen
scrollbar.place(x=580,y=6, height=600)
ChatLog.place(x=6,y=6, height=600, width=578)
EntryBox.place(x=6, y=610, height=85, width=445)
SendButton.place(x=455, y=610, height=85)
if (EntryBox.get("1.0",'end-1c').strip() == ''):
SendButton['state'] = tk.DISABLED
elif EntryBox.get("1.0",'end-1c').strip() != '':
SendButton['state'] = tk.NORMAL
def temp(event):
print(EntryBox.get("1.0",'end-1c').strip() == '')
base.bind('<Return>', temp)
base.mainloop()
I have tried to achieve what I needed by using the if statement:我试图通过使用 if 语句来实现我所需要的:
if (EntryBox.get("1.0",'end-1c').strip() == ''):
SendButton['state'] = tk.DISABLED
elif EntryBox.get("1.0",'end-1c').strip() != '':
SendButton['state'] = tk.NORMAL
When the entry box is empty I want the send button to be disabled, and when I write text I want it to be enabled.当输入框为空时,我希望发送按钮被禁用,当我写文本时,我希望它被启用。 Please ignore the 'def temp' function, I just wrote it to debug some stuff I had in mind.请忽略“def temp”function,我只是写它来调试我想到的一些东西。
You should put the checking logic in a function and bind this function on <Key>
event of EntryBox
:您应该将检查逻辑放在 function 中,并将此 function 绑定到EntryBox
的<Key>
事件上:
def on_key(event):
s = EntryBox.get('1.0', 'end-1c').strip()
SendButton['state'] = tk.DISABLED if s == '' else tk.NORMAL
EntryBox.bind('<Key>', on_key)
Also set initial state of SendButton
to disabled.还将 SendButton 的初始SendButton
设置为禁用。
SendButton.configure(state='disabled') SendButton.configure(state='disabled')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.