[Tkinter] Button States - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] Button States (/thread-32095.html) |
Button States - Oshadha - Jan-20-2021 Script from tkinter import * root = Tk() def my_fun(): #make the my_btn state disabled #do some thing else my_btn = Button(root, text = "CLICK ME", command = my_fun).pack()How do I actually make my_fun do what it's supposed to do?
RE: Button States - buran - Jan-20-2021 You need to organize your code as class import tkinter as tk class App(tk.Frame): def __init__(self, root): super().__init__(root) self.root = root self.btn = tk.Button(root, text = "CLICK ME", command = self.my_callback) self.btn.pack() self.lbl = tk.Label(text = 'Click button...') self.lbl.pack() def my_callback(self): self.btn["state"] = tk.DISABLED self.lbl['text'] = 'Button clicked and disabled' if __name__ == '__main__': root = tk.Tk() root.geometry("300x100") app = App(root) app.mainloop() RE: Button States - deanhystad - Jan-20-2021 What do you think my_btn is after this code executes? If you don't know you should find out. my_btn = Button(root, text = "CLICK ME", command = my_fun).pack()Classes are a good idea for GUI applications because they combine functions with a private namespace that holds all the related variables. It makes for a very clean solution. But classes are not required. Below is an example that passes the required information as an argument to the callback. import random from tkinter import * colors = ['red', 'green', 'blue', 'orange', 'yellow'] def my_fun(button): button['fg'] = random.choice(colors) root = Tk() b1 = Button(root, text = "CLICK ME") b1.configure(command = lambda : my_fun(b1)) b1.pack() b2 = Button(root, text = "ME TOO") b2.configure(command = lambda : my_fun(b2)) b2.pack() RE: Button States - steve_shambles - Jan-27-2021 I think he just wants to know how to disable a button when clicked. from tkinter import * root = Tk() def my_fun(): #make the my_btn state disabled #do some thing else my_btn.config(state=DISABLED) my_btn = Button(root, text = "CLICK ME", command = my_fun) my_btn.pack()The line you used with .pack on the end won't work in this scenario so I changed that. To re-enable the button change DISABLED to NORMAL. RE: Button States - Oshadha - Feb-01-2021 (Jan-27-2021, 11:31 AM)steve_shambles Wrote: I think he just wants to know how to disable a button when clicked.Tysm it worked! |