我的首个Python Tkinter应用无报错但无法打开窗口求助
问题解决
你的代码核心问题是类的构造函数名称拼写错误:Python中类的初始化构造函数必须是__init__(前后各两个下划线,中间为init),但你写成了__int__,导致初始化方法不会在实例化对象时自动调用,窗口创建和主循环都未执行,因此窗口无法打开。
另外还有两个不影响窗口启动但建议修正的拼写问题:
self.lable应为self.label(Label的正确拼写)- Checkbutton的文本
show ne疑似笔误,建议改为show me
修正后的完整代码:
import tkinter as tk class MyGUI: def __init__(self): # 修正构造函数名称 self.root = tk.Tk() self.label = tk.Label(self.root, text='My message', font=('Arial', 18)) # 修正变量名拼写 self.label.pack(padx=10, pady=10) self.textbox = tk.Text(self.root, font=('Arial', 16)) self.textbox.pack(pady=10, padx=10) self.check_state = tk.IntVar() self.check = tk.Checkbutton(self.root, text='show me', font=('Arial', 16), variable=self.check_state) # 修正文本笔误 self.check.pack(padx=10, pady=10) self.button = tk.Button(self.root, text='Show message', font=('Arial', 18), command=self.show_message) self.button.pack(pady=10, padx=10) self.root.mainloop() def show_message(self): print('aaa') MyGUI()
运行修正后的代码,窗口即可正常打开。
内容的提问来源于stack exchange,提问作者Restea Elias
相关产品推荐
相关产品推荐

