改进一下上面的代码,将布局变成网格布局,美观一点,有四个选项,每个按钮都要添加事件
时间: 2024-03-13 07:47:38 浏览: 14
好的,以下是代码示例:
```python
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.grid()
self.create_widgets()
def create_widgets(self):
# 创建四个按钮
self.btn1 = tk.Button(self, text='选项1', command=self.option1)
self.btn2 = tk.Button(self, text='选项2', command=self.option2)
self.btn3 = tk.Button(self, text='选项3', command=self.option3)
self.btn4 = tk.Button(self, text='选项4', command=self.option4)
# 将按钮放置到网格布局中
self.btn1.grid(row=0, column=0, padx=10, pady=10)
self.btn2.grid(row=0, column=1, padx=10, pady=10)
self.btn3.grid(row=1, column=0, padx=10, pady=10)
self.btn4.grid(row=1, column=1, padx=10, pady=10)
def option1(self):
print('你选择了选项1')
def option2(self):
print('你选择了选项2')
def option3(self):
print('你选择了选项3')
def option4(self):
print('你选择了选项4')
root = tk.Tk()
app = App(master=root)
app.mainloop()
```
这个示例中,我们创建了一个继承自 `tk.Frame` 的应用程序类 `App`,在 `__init__` 方法中设置了网格布局,并调用了 `create_widgets` 方法创建了四个按钮,并将它们添加到了网格布局中。每个按钮都有一个对应的事件处理函数。当用户点击某个按钮时,相应的事件处理函数会被调用。