tk创建数字按钮点击输入
时间: 2023-12-03 18:43:41 浏览: 201
可以使用Tkinter中的Button和Entry组件来实现该功能。具体步骤如下:
1. 导入Tkinter模块。
```python
import tkinter as tk
```
2. 创建主窗口。
```python
root = tk.Tk()
```
3. 创建一个Entry组件用于显示输入的数字。
```python
entry = tk.Entry(root, width=30)
entry.pack()
```
4. 创建数字按钮,并为每个按钮绑定一个点击事件。
```python
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, str(current) + str(number))
button1 = tk.Button(root, text="1", command=lambda: button_click(1))
button2 = tk.Button(root, text="2", command=lambda: button_click(2))
button3 = tk.Button(root, text="3", command=lambda: button_click(3))
button4 = tk.Button(root, text="4", command=lambda: button_click(4))
button5 = tk.Button(root, text="5", command=lambda: button_click(5))
button6 = tk.Button(root, text="6", command=lambda: button_click(6))
button7 = tk.Button(root, text="7", command=lambda: button_click(7))
button8 = tk.Button(root, text="8", command=lambda: button_click(8))
button9 = tk.Button(root, text="9", command=lambda: button_click(9))
button0 = tk.Button(root, text="0", command=lambda: button_click(0))
```
5. 将数字按钮添加到主窗口。
```python
button1.pack()
button2.pack()
button3.pack()
button4.pack()
button5.pack()
button6.pack()
button7.pack()
button8.pack()
button9.pack()
button0.pack()
```
6. 运行主循环。
```python
root.mainloop()
```
完整代码如下:
```python
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(root, width=30)
entry.pack()
def button_click(number):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, str(current) + str(number))
button1 = tk.Button(root, text="1", command=lambda: button_click(1))
button2 = tk.Button(root, text="2", command=lambda: button_click(2))
button3 = tk.Button(root, text="3", command=lambda: button_click(3))
button4 = tk.Button(root, text="4", command=lambda: button_click(4))
button5 = tk.Button(root, text="5", command=lambda: button_click(5))
button6 = tk.Button(root, text="6", command=lambda: button_click(6))
button7 = tk.Button(root, text="7", command=lambda: button_click(7))
button8 = tk.Button(root, text="8", command=lambda: button_click(8))
button9 = tk.Button(root, text="9", command=lambda: button_click(9))
button0 = tk.Button(root, text="0", command=lambda: button_click(0))
button1.pack()
button2.pack()
button3.pack()
button4.pack()
button5.pack()
button6.pack()
button7.pack()
button8.pack()
button9.pack()
button0.pack()
root.mainloop()
```
阅读全文