如何从另一个文件打印 class 函数的文本? (Python)

How to print the text of a function of a class from another file? (Python)

我想在单击复选框后打印文本“Ok, good”。该函数位于外部文件的 class 中。我已经接近解决方案,但我做错了。

我得到错误:Button1_func() missing 1 required positional argument: 'self'

谁能告诉我我错在哪里以及如何解决?谢谢

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")

所以主要问题是函数 Button1_func 不在 class 中,因此不需要 self 所以删除

def Button1_func():
    myclass = class_example()
    myclass.print_function()

也取消缩进 print_function 它不应该在 __init__

里面

终于改了

Button1 = Checkbutton(window, text = "Checkbox 1", variable = Checkbutton1, command=Button1_func())

Button1 = Checkbutton(window, text = "Checkbox 1", variable = Checkbutton1, command=Button1_func)

因为你提供 Button1_func 而不是 运行 它 (Button1_func())

它对我有效

工作代码(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")