class tkinter_toggle_button():
def __init__(self):
self.button = tk.Button(text="Toggle", width=12, relief="raised")
def MakeCommand(self):
print('1')
if self('relief')[-1] == 'sunken':
button.config(relief="raised")
else:
button.config(relief="sunken")
def MakeButtonToggle(self):
print('2')
toggle_btn = tk.Button(text="Toggle", width=12, relief="raised", command=tkinter_toggle_button.MakeCommand)
return toggle_btn
class UI:
def MainWindow():
main_window = tk.Tk()
togglebutton1 = tkinter_toggle_button()
togglebutton = togglebutton1.MakeButtonToggle()
togglebutton.grid(row=0,column=0)
main_window.mainloop()
UI.MainWindow()
我希望这段代码使用init方法创建一个切换按钮。我需要帮助来了解其他模块的init方法。这是正确的方法吗?该代码的输出是:
2
按下按钮后:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Juan\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: MakeCommand() missing 1 required positional argument: 'self'
答案 0 :(得分:1)
这是您尝试执行的工作版本。
该类应使用self.
引用内部变量。
import Tkinter
class tkinter_toggle_button():
def __init__(self, master):
self.button = Tkinter.Button(master, text="Toggle", width=12, relief="raised", command=self.MakeCommand)
def MakeCommand(self):
if self.button.config('relief')[-1] == 'sunken':
self.button.config(relief='raised')
else:
self.button.config(relief='sunken')
class UI:
def MainWindow(self):
main_window = Tkinter.Tk()
togglebutton = tkinter_toggle_button(main_window)
togglebutton.button.grid(row=0,column=0)
main_window.mainloop()
ui = UI()
ui.MainWindow()