如何将Tkinter Button用作方法?绑定函数启动即执行点击无效
Tkinter按钮绑定函数时启动即执行、点击无响应的解决办法
问题核心:你给tk.Button的command参数传值时,直接执行了do_something(the_thing='ook')——这会让程序启动时就调用该函数,而command需要的是不带参数的可调用对象,不是函数执行后的返回值(你的函数返回None,所以点击按钮相当于调用None,自然没反应)。
下面是两种可行的解决方式:
方式一:用lambda表达式包装带参数的函数
通过lambda将带参数的函数调用包装成无参的可调用对象,只有点击按钮时才会执行目标函数:
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) # 用lambda包装带参数的函数调用 button_o.add_button(lambda: do_something(the_thing='ook')) root.mainloop()
方式二:用functools.partial固定函数参数
如果函数参数较多或者偏好更清晰的写法,可以用functools.partial生成一个绑定了固定参数的可调用对象:
import tkinter as tk import functools 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) # 用functools.partial固定参数 button_o.add_button(functools.partial(do_something, the_thing='ook')) root.mainloop()
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

