TK默认button点击
时间: 2023-11-25 22:08:33 浏览: 29
在Tkinter中,可以使用command参数来指定当button被点击时执行的函数。下面是一个示例代码:
```
import tkinter as tk
def button_clicked():
print("Button clicked!")
root = tk.Tk()
button = tk.Button(root, text="Click me!", command=button_clicked)
button.pack()
root.mainloop()
```
在这个例子中,当按钮被点击时,会调用button_clicked()函数并打印出"Button clicked!"。
相关问题
tkinter button 返回值
在Tkinter中,Button的command绑定函数默认是没有返回值的。如果需要获取函数的返回值,可以通过以下两种方式实现:
1.使用全局变量:在函数中定义一个全局变量,将需要返回的值赋给该变量,然后在Button外部使用该变量即可获取返回值。
```python
import tkinter as tk
def fake_data():
global result
# 处理数据
result = '处理后的数据'
root = tk.Tk()
button = tk.Button(root, text='处理数据', font=('微软雅黑', 12), command=fake_data)
button.grid(row=1, column=1, padx=10, pady=10)
# 在Button外部使用result变量获取返回值
result_label = tk.Label(root, textvariable=result)
result_label.grid(row=2, column=1)
root.mainloop()
```
2.使用类:定义一个类,将需要返回的值作为类的属性,然后在Button外部使用该类的属性即可获取返回值。
```python
import tkinter as tk
class DataProcessor:
def __init__(self):
self.result = None
def fake_data(self):
# 处理数据
self.result = '处理后的数据'
root = tk.Tk()
processor = DataProcessor()
button = tk.Button(root, text='处理数据', font=('微软雅黑', 12), command=processor.fake_data)
button.grid(row=1, column=1, padx=10, pady=10)
# 在Button外部使用processor.result属性获取返回值
result_label = tk.Label(root, textvariable=processor.result)
result_label.grid(row=2, column=1)
root.mainloop()
```
python2.7使用tk
interact实现GUI界面
```
# -*- coding: utf-8 -*-
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.quitButton = tk.Button(self, text='Quit', command=self.quit)
self.quitButton.grid()
app = Application()
app.master.title('Sample application')
app.mainloop()
```
说明:
- `tk.Frame.__init__(self, master)`表示初始化一个Frame对象,master表示父容器,如果没有指定则默认为Tkinter的`Tk()`对象;
- `self.grid()`表示将Frame对象放置在父容器中,如果没有指定则默认为最外层的Tk();
- `self.createWidgets()`表示创建GUI界面中的控件;
- `self.quitButton = tk.Button(self, text='Quit', command=self.quit)`表示创建一个Button控件,self表示该控件的父容器为Frame对象,text表示按钮上显示的文字,command表示点击按钮时调用`self.quit`方法;
- `self.quitButton.grid()`表示将按钮控件放置在父容器中。
更多控件的使用可以参考[官方文档](https://docs.python.org/2/library/tkinter.html)。