I'm building a tkinter app and as a part of it the user has to upload a file, write a message and then press a Button
whose command runs in another thread.
self.sidebar_button = Button(self.sidebar_frame, text="send your message",
command=threading.Thread(target=send_msg).start)
If the Button
is pressed in the right condition then everything is fine.
However, if the user doesn't upload the file and write the message before pressing the Button
then i show the user an error message. The problem here is that since the first Button
press has started the thread, it can't start again.
Can you think of a workaround for this problem?
Is it possible to disable the Button
before the right conditions are met?
CodePudding user response:
try this:
root = Tk()
message = Entry(root)
def thread():
while True:
if message.get():
butt.config(state=NORMAL)
else:
butt.config(state=DISABLED)
butt = Button(root , text= 'continue', state = DISABLED)
butt.pack()
Thread(target=thread).start()
CodePudding user response:
Look at this:
import tkinter as tk
# This is called each time there is a change in the entry
def check_conditions(*args):
message_text = message_var.get()
# Here we check the conditions:
if message_text == "":
button.config(state="disabled")
else:
button.config(state="normal")
def send():
message_text = message_var.get()
print(f"Send: {message_text!r}")
root = tk.Tk()
message_var = tk.StringVar(root)
# When the value of the `message_var` has changed, call `check_conditions`
message_var.trace("w", check_conditions)
# Create the entry and attach `message_var`
message = tk.Entry(root, textvariable=message_var)
message.pack()
button = tk.Button(root, text="Send", command=send, state="disabled")
button.pack()
root.mainloop()
It uses <tk.StringVar>.trace("w", <function>)
to call check_conditions
each time the user changes the entry. For more info, read this.
tkinter
doesn't always like being called from other threads, so avoid using threading
when using tkinter
.