MA8
MA8

Reputation: 1

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?

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.

Upvotes: 0

Views: 531

Answers (2)

acw1668
acw1668

Reputation: 46669

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.

Upvotes: 1

coderoftheday
coderoftheday

Reputation: 2075

SendButton.configure(state='disabled')

Upvotes: 0

Related Questions