0

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()
Tony
  • 76
  • 6

2 Answers2

3

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()
1

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()
Tony
  • 76
  • 6
  • 2
    Most of the time, decorators are just too much of a pain. Instead, you can use `button_o.add_button(lambda: do_something(the_thing='ook')` - kike the other answer to this question. Lambdas are a bit like decorators when used like that. – TheLizzard Sep 18 '22 at 12:03