how to use tkinter button as a method

Viewed 25

I want to use a tkinter button as a method but the function the button is meant to call runs immediately after starting the program and does not run subsequently.

import tkinter as tk

class Button():
    def __init__(self,window):
        self.window = window
    def add_button(self, func):
        tk.Button(self.window, text='print', command=func).pack()

def do_something(the_thing):
    print(f'{the_thing}')
    return 

root = tk.Tk()
button_o = Button(root)
button_o.add_button(do_something(the_thing='ook'))

root.mainloop()
2 Answers

You can use lambda function here

import tkinter as tk

class Button():
    def __init__(self,window):
        self.window = window
    def add_button(self, func):
        tk.Button(self.window, text='print', command=func).pack()

def do_something(the_thing):
    print(f'{the_thing}')
    return 

root = tk.Tk()
button_o = Button(root)
button_o.add_button(lambda:do_something(the_thing='ook'))

root.mainloop()

just realized i could decorate the function.

import tkinter as tk
class Button():
    def __init__(self,window):
        self.window = window
    def add_button(self, func):
        tk.Button(self.window, text='print', command=func).pack()
def decorator(the_thing):
    def do_something():
        print(f'{the_thing}')
    return do_something

root = tk.Tk()
button_o = Button(root)
button_o.add_button(decorator(the_thing='ook'))

root.mainloop()
Related