如何根据框中是否有文本禁用Python tkinter中的按钮?

2024-05-19 05:51:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问,如何根据输入框中是否有文本,将Python Tkinter中按钮的状态从禁用更改为正常

我已经复制了这段代码,我正在尝试修改它以供练习。请随意运行,以便更简单地理解我的问题

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()

我试图通过使用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

当输入框为空时,我希望禁用“发送”按钮,当我写入文本时,我希望启用该按钮。请忽略“def temp”函数,我写它只是为了调试一些我想到的东西


Tags: basegetcreateplacewidth按钮tkend
2条回答

您应该将检查逻辑放入函数中,并在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)

还将SendButton的初始状态设置为禁用

SendButton.configure(state='disabled')

相关问题 更多 >

    热门问题