I have to execute several functions with one button click. The functions have multiple variables. I think I'm pretty close to get it working but when I click the button the error TypeError: all_functions.function_1() missing 1 required positional argument: 'self'
occurs.
But when I add self
in this manner: all_functions.function_1(self)
I reveive another error which says NameError: name 'self' is not defined
. I wonder why all_functions.function_1
gets recognized perfectly fine while self
does not.
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()
CodePudding user response:
You need to instantiate the class first:
af = all_functions() # ← Create instance, which activates self
create_button = tk.Button(root, command=lambda:[af.function_1(), af.function_2()], text="Button")
CodePudding user response:
It is because you are not instantiating an object of the class. Use
create_button = tk.Button(root, command=lambda:[all_functions().function_1(), all_functions().function_2()], text="Button")
instead of
create_button = tk.Button(root, command=lambda:[all_functions.function_1(), all_functions.function_2()], text="Button")