如何在Tkinter中把輸入框中的字串轉換成整數。 我已經試過了,但沒有用。
import tkinter
from tkinter import tt
age= tkinter.Label(window, text = "How old are you?" )
age.grid(row = 1, column = 0)
entry_age = tkinter.Entry(window)
Entry.grid(row = 1, column = 1)
height = tkinter.Label(window, text = "What is your height(cm): ")
height.grid(row = 2, column = 0)
entry_height = tkinter.Entry(window)
entry_height.grid(row = 2, column = 1)
weight = tkinter.Label(window, text = "你的體重(kg)。")
weight.grid(row = 3, column = 0)
entry_weight = tkinter.Entry(window)
entry_weight.grid(row = 3, column = 1)
entry_age1 = entry_age.get()
entry_age1 = int(entry_age1)
entry_heigh1t = entry_height.get()
entry_height1 = int( entry_height1)
entry_weight1 = entry_weight.get()
entry_weight1 = int( entry_weight1)
uj5u.com熱心網友回復:
這里的.get()函式總是以字串形式回傳任何東西。你必須把它轉換為str到int。
這里是一個快速的例子。
import tkinter as tk
win = tk.Tk()
def get_number():
text = ent.get()
try:
num = int(text) # <= Focus here。
print(num)
except:
print("this is not number")
ent = tk.Entry(win)
ent.grid(row=0, column=0, padx=10, pady=10)
btn = tk.Button(win, text="獲取數字", command=get_number)
btn.grid(row=1, column=0)
win.mainloop()
uj5u.com熱心網友回復:
光看你發布的內容,我沒發現你的代碼有什么問題。請將你得到的錯誤資訊與一些測驗案例一起發布,作為輸入的條目框。
entry_age.get()回傳一個字串,如果輸入的是一個數字,可以用int()轉換為一個整數。
在 @Milena Pavlovic 回復錯誤后編輯:
程式無法運行,因為一旦運行陳述句entry_age1 = entry_age.get(),將空字串存盤到變數中,接下來的陳述句就會嘗試將這個空字串轉換成一個整數。空字串以""為單位,不能轉換為整數型別。由于這是無效的,所以會引發數值錯誤。為了解決這個問題,你可以做以下修改:
entry_age1 = entry_age.get()
if entry_age1.isdecimal()。
entry_age1 = int( entry_age1)
entry_height1 = entry_height.get()
if entry_height1.isdecimal()。
entry_height1 = int( entry_height1)
entry_weight1 = entry_weight.get()
if entry_weight1.isdecimal():
entry_weight1 = int( entry_weight1)
isdecimal()函式檢查get()回傳的字串是否是小數,只有這樣,它才會被轉換成整數并存盤到相應的變數中,并允許你對它們做你想做的事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324460.html
標籤:
上一篇:改變一個應用程式的行為,如何根據一個數字隱藏一個結賬按鈕,這個數字是由一個總和和一個貨幣符號組成的字串的一部分?
