使用 Tkinter 构建 GUI [英] Building GUIs with Tkinter
问题描述
我正在尝试使用 Tkinter 制作一个 GUI,您可以在其中输入两个数字并将它们相加.我不确定如何在我的窗口中显示答案.此外,当我运行它时,会出现一个错误:类型错误:+ 不支持的操作数类型:条目"和条目"
I'm trying to make a GUI with Tkinter where you type two numbers in and it adds them together. I'm unsure how to display the answer in my window. Also when I run it there is an error which says: TypeError: unsupported operand type(s) for +: 'Entry' and 'Entry'
from tkinter import *
window = Tk()
def add():
label = Label(window, text=entry1 + entry2)
entry1 = Entry(window, width=10)
entry2 = Entry(window, width=10)
button = Button(window, text='Click to add', command=add)
entry1.pack()
entry2.pack()
button.pack()
label.pack()
如果有人能帮我修复我的代码,我将不胜感激.
If someone could help me fix my code I would greatly appreciate it.
推荐答案
您的代码包含许多错误.您不能直接使用条目字段,而是需要在条目字段中添加值.还需要添加tkinter的主循环处理.
Your code contains a number of mistakes. You cannot directly use the Entry field, instead you need to add the values in the Entry field. You also need to add the main loop processing of tkinter.
以下是一个没有任何错误处理的快速运行示例(如果您没有为输入字段之一输入值,则失败),
Following is a quick running example without any error handling (It fails if you don't enter values for one of the Entry fields),
import tkinter
mainWindow = tkinter.Tk()
mainWindow.title("Demo App")
mainWindow.geometry("640x480+200+200")
entry1 = tkinter.Entry(mainWindow,width=10)
entry2 = tkinter.Entry(mainWindow,width=10)
entry1.pack()
entry2.pack()
label = tkinter.Label(mainWindow,text="Click on add to add numbers")
label.pack()
def add_values():
result = int(entry1.get()) + int(entry2.get())
label['text'] = result
button = tkinter.Button(mainWindow,text="Add",command=add_values)
button.pack()
mainWindow.mainloop()
这篇关于使用 Tkinter 构建 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!