Python-如何从 tkinter 小部件获取值并将其分配给变量 [英] Python-How to get the value from tkinter widget and assign it to a variable

查看:54
本文介绍了Python-如何从 tkinter 小部件获取值并将其分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from tkinter import *
import tkinter as tk
import pyodbc

root1 = tk.Tk()

label1 = tk.Label(root1, text='product A')
entry1 = tk.Entry(root1)

label1.pack(side = tk.TOP)
entry1.pack()
input1= StringVar()
input1.set(entry1.get())
print (input1)

此代码用于将输入文本框小部件的值分配给变量 Input1.但是,我得到的值是:PY_VAR0 而不是 Entry1 中的文本.

This code is used to assign the value from the input textbox widget to a variable-Input1. However,the value I get is:PY_VAR0 instead of the text in Entry1.

我需要打印输入文本.为什么会出现 PY_VAR0?

I need to print the input text. Why is PY_VAR0 appearing?

请帮忙.

谢谢.

推荐答案

问题是您在用户有机会键入任何内容之前获取了条目小部件的值,因此它始终是空字符串.

The problem is that you're getting the value of the entry widget before the user has a chance to type anything, so it will always be the empty string.

如果您等到用户输入内容后才执行 get,您的代码将按原样正常工作.不过,我认为没有任何理由使用 StringVar,因为它只是添加了一个没有实际用途的额外对象.没有理由将 StringVar 与入口小部件一起使用,除非您需要 StringVar 为您提供的额外功能——即变量跟踪.

If you wait to do the get until after the user enters something, your code will work fine as-is. Though, I don't see any reason to use a StringVar as it just adds an extra object that serves no real purpose. There's no reason to use a StringVar with an entry widget unless you need the extra features that a StringVar gets you -- namely, variable traces.

您看到 PY_VAR0 的原因是您必须使用 get 方法从 StringVar 的实例中获取值.将您的语句更改为 print input1.get().

The reason you are seeing PY_VAR0 is because you must use the get method to get the value out of an instance of StringVar. Change your statement to print input1.get().

这篇关于Python-如何从 tkinter 小部件获取值并将其分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆