[英]how can i get a integar value from python tkinter entry?
所以我知道 python 中的條目是如何工作的,並且我在一些項目中對其進行了編碼。 但在一個項目中,需要在輸入時從用戶那里獲取數字 ( number ) 值。 但它給出了條目僅支持字符串數據的錯誤。 你能解決這個問題嗎? 謝謝。
您只需要將其類型轉換為 integer。例如。 這段代碼對我有用:
from tkinter import *
win=Tk()
win.geometry("700x350")
def cal_sum():
t1=int(a.get()) # Casting to integer
t2=int(b.get()) # Casting to integer
sum=t1+t2
label.config(text=sum)
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()
為了進一步補充這一點,您可以使用驗證來確保您只能在條目中寫入評估為 integer 的值:
import tkinter as tk
root = tk.Tk()
root.geometry("200x100")
# Function to validate the Entry text
def validate(entry_value_if_allowed, action):
if int(action) == 0: # User tried to delete a character/s, allow
return True
try:
int(entry_value_if_allowed) # Entry input will be an integer, allow
return True
except ValueError: # Entry input won't be an integer, don't allow
return False
# Registering the validation function, passing the correct callback substitution codes
foo = (root.register(validate), '%P', '%d')
my_entry = tk.Entry(root, width=20, validate="key", validatecommand=foo)
# Misc
text = tk.Label(root, text="This Entry ^ will only allow integers")
my_entry.pack()
text.pack()
root.mainloop()
可以在此處找到有關條目驗證的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.