import tkinter as tk root = tk.Tk() root.title("简单计算器和标签") root.geometry("300x200") num1 = tk.StringVar() num2 = tk.StringVar() result = tk.StringVar() result.set("") def add(): global num1, num2, result x = float(num1.get()) y = float(num2.get()) result.set(str(x+y)) tk.Label(root, text="名字:").grid(row=0, column=0) tk.Entry(root).grid(row=0, column=1) tk.Label(root, text="学号:").grid(row=1, column=0) tk.Entry(root).grid(row=1, column=1) tk.Label(root, text="请输入两个数字:").grid(row=2, column=0, columnspan=2) entry1 = tk.Entry(root, textvariable=num1) entry1.grid(row=3, column=0) entry2 = tk.Entry(root, textvariable=num2) entry2.grid(row=3, column=1) button = tk.Button(root, text="相加", command=add) button.grid(row=4, column=0, columnspan=2) label1 = tk.Label(root, text="计算结果:") label1.grid(row=5, column=0) label2 = tk.Label(root, textvariable=result) label2.grid(row=5, column=1) root.mainloop()不能运行
时间: 2024-01-11 11:03:22 浏览: 107
如何利用python的tkinter实现一个简单的计算器.docx
这段代码是可以运行的,但是存在一个问题:在函数`add()`中,使用了全局变量`num1`,`num2`,`result`,但是这些变量没有在函数中声明为全局变量。可以在函数中添加`global`关键字声明这些变量为全局变量,如下所示:
```python
def add():
global num1, num2, result
x = float(num1.get())
y = float(num2.get())
result.set(str(x+y))
```
另外,你在代码中创建了两个`Entry`控件,但是没有保存它们的输入值,需要将它们的`textvariable`参数设置为相应的`StringVar`对象,如下所示:
```python
entry1 = tk.Entry(root, textvariable=num1)
entry1.grid(row=3, column=0)
entry2 = tk.Entry(root, textvariable=num2)
entry2.grid(row=3, column=1)
```
修改后的完整代码如下:
```python
import tkinter as tk
root = tk.Tk()
root.title("简单计算器和标签")
root.geometry("300x200")
num1 = tk.StringVar()
num2 = tk.StringVar()
result = tk.StringVar()
result.set("")
def add():
global num1, num2, result
x = float(num1.get())
y = float(num2.get())
result.set(str(x+y))
tk.Label(root, text="名字:").grid(row=0, column=0)
tk.Entry(root).grid(row=0, column=1)
tk.Label(root, text="学号:").grid(row=1, column=0)
tk.Entry(root).grid(row=1, column=1)
tk.Label(root, text="请输入两个数字:").grid(row=2, column=0, columnspan=2)
entry1 = tk.Entry(root, textvariable=num1)
entry1.grid(row=3, column=0)
entry2 = tk.Entry(root, textvariable=num2)
entry2.grid(row=3, column=1)
button = tk.Button(root, text="相加", command=add)
button.grid(row=4, column=0, columnspan=2)
label1 = tk.Label(root, text="计算结果:")
label1.grid(row=5, column=0)
label2 = tk.Label(root, textvariable=result)
label2.grid(row=5, column=1)
root.mainloop()
```
阅读全文