如何在 Tkinter 中將 Entry.get() 變數轉換為整數?


Tkinter 控制元件的 Entry 通常用於以文字形式獲得單行輸入。我們可以使用 .get() 方法從 Entry 控制元件獲取輸出。不過,.get() 方法返回字串格式的輸出。例如,如果使用者在 Entry 控制元件中輸入整數,該整數會轉換為字串。如需將 Entry 輸入的型別更改為整數,我們可以將字串轉換為整數。

示例

在此示例中,我們展示瞭如何在從使用者獲取整數輸入時計算和。下面是具體方法:

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the tkinter window
win.geometry("700x350")

def cal_sum():
   t1=int(a.get())
   t2=int(b.get())
   sum=t1+t2
   label.config(text=sum)

# Create an Entry widget
Label(win, text="Enter First Number", font=('Calibri 10')).pack()
a=Entry(win, width=35)
a.pack()
Label(win, text="Enter Second Number", font=('Calibri 10')).pack()
b=Entry(win, width=35)
b.pack()

label=Label(win, text="Total Sum : ", font=('Calibri 15'))
label.pack(pady=20)

Button(win, text="Calculate Sum", command=cal_sum).pack()

win.mainloop()

輸出

更新日期:2021 年 8 月 6 日

1.8 萬次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告