如何从 python tkinter 条目中获取整数值?
how can i get a integar value from python tkinter entry?
所以我知道 python 中的条目是如何工作的,并且我在一些项目中对其进行了编码。但在一个项目中,需要在输入时从用户那里获取数字 (number) 值。但它给出了条目仅支持字符串数据的错误。你能解决这个问题吗?谢谢。
您只需将其类型转换为整数即可。例如。此代码对我有用:
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()
要进一步补充这一点,您可以使用 验证 来确保您只能在条目中写入评估为整数的值:
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()
可以找到有关条目验证的更多信息here。
所以我知道 python 中的条目是如何工作的,并且我在一些项目中对其进行了编码。但在一个项目中,需要在输入时从用户那里获取数字 (number) 值。但它给出了条目仅支持字符串数据的错误。你能解决这个问题吗?谢谢。
您只需将其类型转换为整数即可。例如。此代码对我有用:
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()
要进一步补充这一点,您可以使用 验证 来确保您只能在条目中写入评估为整数的值:
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()
可以找到有关条目验证的更多信息here。