I would like to print the text "Ok, good" after clicking on a checkbox. The function is in a class of an external file. I've come close to the solution, but I'm doing something wrong.
I get error: Button1_func() missing 1 required positional argument: 'self'
Could anyone suggest me what am I wrong and how to fix? Thank you
main.py
from tkinter import *
from tkinter import ttk
import tkinter as tk
from tkinter import ttk
from x import class_example
window=Tk()
window.configure(bg='#f3f2f2')
style = ttk.Style(window)
def Button1_func(self):
myclass = x.class_example(self)
myclass.print_function()
Checkbutton1 = IntVar()
Button1 = Checkbutton(window, text = "Checkbox 1", variable = Checkbutton1, command=Button1_func())
Button1.place(x=1, y=48)
window.mainloop()
x.py
class class_example:
def __init__(self):
self.number = 5
def print_function(self):
if self.number == 5:
print("Ok, good")
CodePudding user response:
So the main problem is that the function Button1_func is not in a class and thus doesn't require self so remove that
def Button1_func():
myclass = class_example()
myclass.print_function()
also unindent the print_function
it should't be inside the __init__
Finaly change the
Button1 = Checkbutton(window, text = "Checkbox 1", variable = Checkbutton1, command=Button1_func())
to
Button1 = Checkbutton(window, text = "Checkbox 1", variable = Checkbutton1, command=Button1_func)
as your providing Button1_func
not running it (Button1_func()
)
and it worked on my side
working code(main.py)
from tkinter import *
from tkinter import ttk
import tkinter as tk
from tkinter import ttk
from x import class_example
window=Tk()
window.configure(bg='#f3f2f2')
style = ttk.Style(window)
def Button1_func():
myclass = class_example()
myclass.print_function()
Checkbutton1 = IntVar()
Button1 = Checkbutton(window, text = "Checkbox 1", variable = Checkbutton1, command=Button1_func)
Button1.place(x=1, y=48)
window.mainloop()
x.py
class class_example:
def __init__(self):
self.number = 5
def print_function(self):
if self.number == 5:
print("Ok, good")