我曾尝试创建一个名为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, indicatoron=False, font=self.font,fg='red',
onvalue=1, offvalue=0, 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()
只需在__init__()
函数中添加一个command
选项,并在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"))
...