單擊復選框后,我想列印文本“Ok, good”。該函式在一個外部檔案的類中。我已經接近解決方案,但我做錯了什么。
我得到錯誤:Button1_func() missing 1 required positional argument: 'self'
誰能建議我我錯了什么以及如何解決?謝謝
主檔案
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")
uj5u.com熱心網友回復:
所以主要問題是函式 Button1_func 不在一個類中,因此不需要 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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438689.html
標籤:Python python-3.x 班级 tkinter 印刷
