我必須一鍵執行幾個功能。這些函式有多個變數。我想我已經很接近讓它作業了,但是當我點擊按鈕時,TypeError: all_functions.function_1() missing 1 required positional argument: 'self'
就會發生錯誤。
但是當我self
以這種方式添加時:all_functions.function_1(self)
我收到另一個錯誤,上面寫著NameError: name 'self' is not defined
. 我想知道為什么all_functions.function_1
得到很好的認可而self
沒有。
import tkinter as tk
class all_functions():
def function_1(self):
self.a = 1
self.b = 2
print(self.a, self.b)
def function_2(self):
self.c = 3
self.d = 4
print(self.c, self.d)
root = tk.Tk()
create_button = tk.Button(root, command=lambda:[all_functions.function_1(), all_functions.function_2()], text="Button")
create_button.grid()
root.mainloop()
uj5u.com熱心網友回復:
您需要先實體化該類:
af = all_functions() # ← Create instance, which activates self
create_button = tk.Button(root, command=lambda:[af.function_1(), af.function_2()], text="Button")
如果這不僅僅是一個虛構的示例,那么可能根本不需要類,因為沒有一個函式共享任何資料。
uj5u.com熱心網友回復:
這是因為您沒有實體化該類的物件。利用
create_button = tk.Button(root, command=lambda:[all_functions().function_1(), all_functions().function_2()], text="Button")
代替
create_button = tk.Button(root, command=lambda:[all_functions.function_1(), all_functions.function_2()], text="Button")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507296.html
下一篇:在OOP中有控制器類是否常見