问题描述
我曾尝试创建一个自定义小部件名称 OnOffButton
,但现在我想在点击小部件时调用一个函数,例如 Button
小部件。
我希望我的小部件中的命令选项像 tkinter.Button
一样。
非常感谢您的帮助。
import tkinter as tk
class OnOffButton(tk.Frame):
def __init__(self,parent,barwidth=3,default='OFF',font='consolas 12 bold'):
tk.Frame.__init__(self,parent)
self.ON = "ON "
self.OFF = 'OFF'
self.space = ' '*barwidth
self.font = font
self.on_variable = tk.Intvar(self,value=0)
self.off_variable = tk.Intvar(self,value=0)
self.state = 0
self.on_btn = tk.Checkbutton(self,text=self.space,indicatoron=False,font=self.font,fg='green',\
onvalue=1,offvalue=0,variable=self.on_variable,command=self.click_on)
self.off_btn = tk.Checkbutton(self,text=self.OFF,fg='red',variable=self.off_variable,command=self.click_off)
self.on_btn.grid(row=0,column=0)
self.off_btn.grid(row=0,column=1)
if default.lower() == 'off':
self.off_btn.select()
self.on_btn.deselect()
else:
self.on_btn.select()
self.off_btn.deselect()
self.on_btn['text'] = self.ON
self.off_btn['text'] = self.space
def click_on(self):
if self.on_variable.get() == 0:
self.off_btn.select()
self.off_btn['text'] = self.OFF
self.on_btn['text'] = self.space
self.state = False
elif self.on_variable.get() == 1:
self.off_btn.deselect()
self.off_btn['text'] = self.space
self.on_btn['text'] = self.ON
self.state = True
def click_off(self):
if self.off_variable.get() == 0:
self.on_btn.select()
self.on_btn['text'] = self.ON
self.off_btn['text'] = self.space
self.state = True
elif self.off_variable.get() == 1:
self.on_btn.deselect()
self.on_btn['text'] = self.space
self.off_btn['text'] = self.OFF
self.state = False
if __name__ == '__main__':
root = tk.Tk()
root.geometry('200x200')
btn = OnOffButton(root)
btn.pack()
root.mainloop()
解决方法
只需在 command
函数中添加一个 __init__()
选项并在 click_on()
和 click_off()
函数中调用传递的回调:
from inspect import isfunction
class OnOffButton(tk.Frame):
def __init__(self,...,command=None): # added command option
...
self.command = command if isfunction(command) else None
...
def click_on(self):
...
if self.command:
self.command()
def click_off(self):
...
if self.command:
self.command()
...
btn = OnOffButton(root,command=lambda: print("clicked"))
...