0

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?

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

2 Answers 2

1

You should put the checking logic in a function and bind this function on <Key> event of 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)

Also set initial state of SendButton to disabled.

Sign up to request clarification or add additional context in comments.

Comments

0

SendButton.configure(state='disabled')

1 Comment

I tried that but it did not work... am I missing anything? I am sorry I am new to GUI programming in Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.