2017-09-24 85 views
0

我在用Tkinter製作一個圖形用戶界面,在其中鍵入兩個數字並將它們添加到一起。我不確定如何在窗口中顯示答案。此外,當我運行它有它說一個錯誤:+不支持的操作類型: 類型錯誤「進入」和「進入」用Tkinter構建圖形用戶界面

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() 

如果有人可以幫助我解決我的代碼,我將不勝感激它。

回答

2

您的代碼包含一些錯誤。您不能直接使用輸入字段,而需要在輸入字段中添加值。您還需要添加tkinter的主循環處理。

以下是沒有任何錯誤處理一個快速運行的例子(如果你沒有爲輸入字段中的一個輸入值它失敗),

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() 
+0

感謝這幫助了很多! –

+1

如果你解釋了你做了什麼不同,你的答案會更好。否則,讀者將被迫將您的代碼與原始的逐行和逐字符比較,以試圖找出您所做的工作。 –

+0

已更新,主要更改。 –

1

你的代碼有一些失誤。首先,你不能通過在它們之間放置一個「+」符號來添加兩個條目。您需要獲取STRING值,然後將其轉換爲INTEGER,添加它們,然後將ENTRY BOX的值設置爲它。 第二個錯誤是你沒有使用MAIN LOOP。如果沒有MAIN LOOP,tkinter GUI將會消失,所以要保證GUI使用LOOP。

使用記事本++。經測試在Windows 7上的Python 2.7

from tkinter import * 

window = Tk() 

#name window 
window.title('My Add') 

#window sized 
window.geometry('250x200') 


def add(): 
    sum = int(entry1.get()) + int(entry2.get()) 
    entry3.delete(0,END) 
    entry3.insert(0,str(sum)) 

L1 = Label(window, text='Number 1:')  
entry1 = Entry(window, width=20) 
L1.pack() 
entry1.pack() 

L2 = Label(window, text='Number 2:') 
entry2 = Entry(window, width=20) 
L2.pack() 
entry2.pack() 

button = Button(window, text='Click to add', command=add) 
button.pack() 

L3 = Label(window, text='Sum of Number 1 and Number 2:') 
entry3 = Entry(window, width=20) 
L3.pack() 
entry3.pack() 

window.mainloop() 

enter image description here

+0

如果你解釋了你做了什麼不同,你的答案會更好。否則,讀者將被迫將您的代碼與原始的逐行和逐字符比較,以試圖找出您所做的工作。 –

+0

將確保它下次。 –

+0

你總是可以回去編輯你的答案。 –