import tkinter as tkfrom tkinter import messagebox # 导入子模块classMyApplication: """一个使用类的典型Tk应用结构,更易于管理""" def __init__(self): # 1. 创建主窗口 self.root = tk.Tk() self.root.title("标准应用模板") self.root.geometry("500x400") # 2. 构建界面 self._create_widgets() # 3. 绑定事件 (可选) self.root.protocol("WM_DELETE_WINDOW", self.on_closing) def _create_widgets(self): """创建和放置所有控件""" self.label = tk.Label(self.root, text="欢迎使用", font=("Arial", 16)) self.label.pack(pady=20) self.entry = tk.Entry(self.root, width=30) self.entry.pack(pady=10) self.entry.insert(0, "输入一些内容") self.button = tk.Button(self.root, text="点击我", command=self.on_button_click) self.button.pack(pady=10) self.text = tk.Text(self.root, height=10) self.text.pack(fill="both", expand=True, padx=20, pady=10) def on_button_click(self): """按钮点击事件的回调函数""" content = self.entry.get() self.text.insert("end", f"你输入了:{content}\n") self.entry.delete(0, "end") # 清空输入框 def on_closing(self): """关闭窗口时的确认""" if messagebox.askokcancel("退出", "确定要退出程序吗?"): self.root.destroy() # 销毁窗口,结束mainloop def run(self): """启动应用""" self.root.mainloop()if __name__ == "__main__": app = MyApplication() app.run() # 进入主事件循环