简体   繁体   English

如何从 python tkinter 条目中获取整数值?

[英]how can i get a integar value from python tkinter entry?

so I know how entry in python works and i coded it in some projects.所以我知道 python 中的条目是如何工作的,并且我在一些项目中对其进行了编码。 but in one project, there was need to get numeric ( number ) value from user in entry.但在一个项目中,需要在输入时从用户那里获取数字 ( number ) 值。 but it gives the error that entry only supports string data.但它给出了条目仅支持字符串数据的错误。 can you solve this problem?你能解决这个问题吗? thanks.谢谢。

You just need to typecast it into an integer. Eg.您只需要将其类型转换为 integer。例如。 This code worked for me:这段代码对我有用:

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()

To add further to this, you can use validation to ensure that you can only write values that evaluate to an integer in your entry:为了进一步补充这一点,您可以使用验证来确保您只能在条目中写入评估为 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()

Some more info on Entry validation can be found here .可以在此处找到有关条目验证的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM