用python写一个GUI和逻辑代码分开的程序
时间: 2023-03-23 12:02:33 浏览: 233
好的,下面是一个用Python写的GUI程序和它对应的交互式代码:
GUI程序:
```python
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
交互式代码:
```python
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
# 创建主窗口
root = tk.Tk()
# 创建应用程序对象
app = Application(master=root)
# 开始事件循环
app.mainloop()
```
这个程序使用了Python的标准GUI库Tkinter来创建一个简单的窗口,其中包含一个按钮和一个退出按钮。当用户单击按钮时,程序会在控制台输出“hi there, everyone!”。这个程序还实现了一个Application类,继承了Tkinter的Frame类,并重写了它的__init__()方法和create_widgets()方法来创建GUI组件。在这个例子中,我们将Application类的实例化和开始事件循环分别放在了两个不同的代码块中。
阅读全文