#python #python-3.x #user-interface #tkinter
#python #python-3.x #пользовательский интерфейс #tkinter
Вопрос:
Я хотел бы спросить, как я могу изменить состояние кнопки в 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’, я просто написал ее для отладки некоторых вещей, которые я имел в виду.
Ответ №1:
Вы должны поместить логику проверки в функцию и привязать эту функцию к <Key>
событию EntryBox
:
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
на отключенное.
Ответ №2:
SendButton.configure(состояние = ‘отключено’)
Комментарии:
1. Я пробовал это, но это не сработало … я что-то пропустил? Извините, я новичок в программировании с графическим интерфейсом на Python.