【发布时间】:2021-07-31 14:58:01
【问题描述】:
我试图创建一个自定义小部件名称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()
【问题讨论】:
标签: python python-3.x tkinter widget tk