2017-04-17 151 views
0

我需要弄清楚如何讓代碼的數學部分出現在tkinter窗口上,我該怎麼做?感謝您的幫助向tkinter添加字符串

from tkinter import * 
def Maths(): 
    kph = 0 
    for x in range(12): 
     kph = kph + 10 
     mph = kph * 0.6214 
     print(kph,"   ",mph) 

def main(): 
    app = Tk() 
    app.title("kph to mph") 
    app.geometry('300x450') 


Label(app, text="KPH to MPH converter").pack() 
Label(app, text="-----------------------------").pack() 
Label(app, text="KPH      MPH").pack() 
Label(app, text="-----------------------------").pack() 
b1 = Button(app, text="Convert", command=Maths) 

b1.pack(side='bottom') 

app.mainloop() 
main() 
+0

目前還不清楚你在問什麼,但看起來你只需要一對[條目](http://effbot.org/tkinterbook/entry.htm)來顯示速度。一個用於'kph',另一個用於'mph'。 – CommonSense

+0

我開始不得不製作一個程序,將kph值從1-12轉換爲等效的mph速度。但是,現在我需要爲該程序創建一個接口,並且我不知道如何讓代碼的主要部分顯示,而不必將它們全部添加爲自己的標籤。 – Tobleh

+0

「將它們全部添加爲自己」有什麼問題?您可以爲此目的使用[this](http://stackoverflow.com/a/11049650/6634373)代碼段。只是一張看起來像一張桌子的標籤。如果您願意,您可以從標籤切換到條目。如果你不喜歡它 - 你可以嘗試[listbox/treeview](https://www.daniweb.com/programming/software-development/threads/350266/creating-table-in-python)小部件。 – CommonSense

回答

0

我看到你最終使用了一個列表,但我想你可能會覺得這很有幫助。 Tkinter標籤具有內置的textvariable選項,您可以設置它,並且會在設置StringVar()時進行更新。我修改了數學函數,將輸出設置爲標籤中添加的StringVar。測試和工作。

from tkinter import * 

def Maths(): 
    #New Code 
    temp = "" 

    kph = 0 
    for x in range(12): 
     kph = kph + 10 
     mph = kph * 0.6214 

     #New Code 
     temp += ("%d   %d\n" % (kph,mph)) 
    output.set(temp) 

app = Tk() 
app.title("kph to mph") 
app.geometry('300x450') 

Label(app, text="KPH to MPH converter").pack() 
Label(app, text="-----------------------------").pack() 
Label(app, text="KPH      MPH").pack() 
Label(app, text="-----------------------------").pack() 
b1 = Button(app, text="Convert", command=Maths) 
b1.pack(side='bottom') 

#New Code 
output = StringVar() 
Label(app, textvariable=output).pack() 

app.mainloop()