1 回答
TA贡献1802条经验 获得超5个赞
这是解决方案:
如果您.grid()在同一行中使用number1,number2则将返回None,我们无法获取数据。
所做的更改如下:
number1=tk.Entry(multi_add, textvariable = num1)
number2=tk.Entry(multi_add, textvariable = num2)
number1.grid(row=0, column=1)
number2.grid(row=1, column=1)
和
def result():
num3 = float(number1.get()) + float(number2.get())
num4 = float(number1.get()) * float(number2.get())
这是整个代码:
import tkinter as tk
'''OS'''
root = tk.Tk()
root.title("Simple Box")
operator=""
canvas = tk.Canvas(root, height=400,width=500,bg="White")
canvas.pack()
frame=tk.Frame(root, bg="Light Blue")
frame.place(relwidth=0.9,relheight=0.9, relx=0.05, rely=0.05)
'''Variable '''
num1= tk.StringVar()
num2= tk.StringVar()
''' function'''
def operation1():
global number1, number2
multi_add =tk.Tk()
multi_add.title("Multiplication and Addition")
tk.Label(multi_add, font =("Helvetica", 20),
text="Enter the first number:").grid(row=0)
tk.Label(multi_add, font =("Helvetica", 20),
text="Enter the second number").grid(row=1)
number1=tk.Entry(multi_add, textvariable = num1)
number2=tk.Entry(multi_add, textvariable = num2)
number1.grid(row=0, column=1)
number2.grid(row=1, column=1)
def result():
num3 = float(number1.get()) + float(number2.get())
num4 = float(number1.get()) * float(number2.get())
print("the result is ",num3 ,"and", num4)
'''buttons'''
result=tk.Button(frame, text="Result", font=('airal', 30 ,'bold'), height="1"
,width="6", padx=10,pady=5, fg="Black",
bg="yellow", command= result)
result.place(x=300 , y=305)
op1=tk.Button(frame, text="operation 1", height="2", width="10", padx=10,
pady=5, fg="Black", bg="yellow", command = operation1)
op1.place(x = 17, y = 310)
root.mainloop()
和第二种方法
无需声明变量num1和num2:
import tkinter as tk
'''OS'''
root = tk.Tk()
root.title("Simple Box")
operator=""
canvas = tk.Canvas(root, height=400,width=500,bg="White")
canvas.pack()
frame=tk.Frame(root, bg="Light Blue")
frame.place(relwidth=0.9,relheight=0.9, relx=0.05, rely=0.05)
''' function'''
def operation1():
global number1, number2
multi_add =tk.Tk()
multi_add.title("Multiplication and Addition")
tk.Label(multi_add, font =("Helvetica", 20),
text="Enter the first number:").grid(row=0)
tk.Label(multi_add, font =("Helvetica", 20),
text="Enter the second number").grid(row=1)
number1=tk.Entry(multi_add)
number2=tk.Entry(multi_add)
number1.grid(row=0, column=1)
number2.grid(row=1, column=1)
def result():
num3 = float(number1.get()) + float(number2.get())
num4 = float(number1.get()) * float(number2.get())
print("the result is ",num3 ,"and", num4)
'''buttons'''
result=tk.Button(frame, text="Result", font=('airal', 30 ,'bold'), height="1"
,width="6", padx=10,pady=5, fg="Black",
bg="yellow", command= result)
result.place(x=300 , y=305)
op1=tk.Button(frame, text="operation 1", height="2", width="10", padx=10,
pady=5, fg="Black", bg="yellow", command = operation1)
op1.place(x = 17, y = 310)
root.mainloop()
添加回答
举报