Python - 如何获取条目小部件而不是连接?

时间:2017-09-16 22:41:33

标签: python tkinter

我想获得两个单独的条目小部件来添加其中的内容,但现在的问题是它是连接条目小部件中的数字。

from tkinter import *

master = Tk()

class MainWindow:
    def __init__(self, master):
        self.master = master
        master.geometry("640x480")


def Calculate():
    entry1 = firstEntry.get()
    entry2 = secondEntry.get()
    result = entry1 + entry2
    print(result)


firstLabel = Label(text="First Value")
firstLabel.grid(row=1, column=1)

firstEntry = Entry(master)
firstEntry.grid(row=1, column=2)

addLabel = Label(text="+")
addLabel.grid(row=1, column=3)

secondEntry = Entry(master)
secondEntry.grid(row=1, column=4)

secondLabel = Label(text="Second Value")
secondLabel.grid(row=1, column=5)

equalsButton = Button(text="=", width=10, command=Calculate)
equalsButton.grid(row=2, column=3)

master.mainloop()

2 个答案:

答案 0 :(得分:0)

from tkinter import *

master = Tk()

class MainWindow:
    def __init__(self, master):
        self.master = master
        master.geometry("640x480")


def Calculate():
    entry1 = firstEntry.get()
    entry2 = secondEntry.get()
    result = int(entry1) + int(entry2)
    print(result)


firstLabel = Label(text="First Value")
firstLabel.grid(row=1, column=1)

firstEntry = Entry(master)
firstEntry.grid(row=1, column=2)

addLabel = Label(text="+")
addLabel.grid(row=1, column=3)

secondEntry = Entry(master)
secondEntry.grid(row=1, column=4)

secondLabel = Label(text="Second Value")
secondLabel.grid(row=1, column=5)

equalsButton = Button(text="=", width=10, command=Calculate)
equalsButton.grid(row=2, column=3)

master.mainloop()

只需通过int(firstentry.get())和int(secondentry.get())对entry.get的结果进行类型转换,否则会导致添加字符串

" 4" +" 5" =" 45"

答案 1 :(得分:0)

问题在于,Python中的+运算符具有字符串和数字(​​以及其他)的含义。 对于数字,它代表了自然(在#34;常见"意义上)添加:

>>> 1 + 1
2

另一方面,对于字符串,它代表串联:

>>> "Hello" + ", world!"
'Hello, world!"

get实例的tkinter.Entry方法返回一个字符串对象,即str的实例。 因此,entry1 = firstEntry.get()entry2 = secondEntry.get()都会为您提供一个字符串,无论输入是否包含数字。 然后,entry1 + entry2会生成一个字符串,即entry1entry2的串联。

因此,您需要事先将条目的内容转换为整数或浮点数,后者更为通用。 您的Calculate功能可能会变为:

def Calculate():
    entry1 = float(firstEntry.get())
    entry2 = float(secondEntry.get())
    result = entry1 + entry2
    print(result)

但请注意,如果无法执行转换,float函数将引发ValueError。 以下将更加谨慎:

def Calculate():
    try:
        entry1 = firstEntry.get()
        entry2 = secondEntry.get()
        result = entry1 + entry2
        print(result)
    except ValueError:
        print("Please type in valid numbers")