如何从 Entry 小部件获取文本 [英] How to get text from Entry widget

查看:55
本文介绍了如何从 Entry 小部件获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 stackOverflow 上看了几篇解释了答案的帖子,但无论我使用哪个,我都无法从我的条目小部件中获取字符串;它只是检测到一串"

I've looked at several posts on stackOverflow that explain the answer but no matter which I use, I never can get the string from my entry widget; it just detects a string of ""

这是我的代码:

def buttonTest():
    global score
    gui.title("Test")
    for child in gui.winfo_children():
        child.destroy()
    global questionText
    global questionAnswer
    questionText = StringVar()
    questionAnswer = 0    
    question = Label(gui, textvariable = questionText, fg = "black", bg = "white")
    question.grid(row = 0, column = 1)
    userInput = StringVar()
    input = Entry(gui, textvariable = userInput)
    input.grid(row = 1, column = 0)

swapQuestion()

checkAns = Button(text = "Check answer", command = partial(checkAnswer, userInput.get(), questionAnswer), fg = "black", width=10)
checkAns.grid(row = 1, column = 2)

推荐答案

请阅读并关注此 SO 帮助页面.您的代码缺少运行所需的行,并且包含与您的问题无关的行.它也缺少缩进.

Please read and follow this SO help page. Your code is missing lines needed to run and has lines that are extraneous to your question. It is also missing indentation.

您的问题是您在创建按钮时只调用了一次 userInput.get(),然后用户才能输入任何内容.当时,它的值确实是''.您必须在按钮命令函数中调用它,每次按下按钮时都会调用该函数.

Your problem is that you call userInput.get() just once, while creating the button, before the user can enter anything. At that time, its value is indeed ''. You must call it within the button command function, which is called each time the button is pressed.

这是一个既能运行又能工作的最小完整示例.

Here is a minimal complete example that both runs and works.

import tkinter as tk

root = tk.Tk()

user_input = tk.StringVar(root)
answer = 3

def verify():
    print(int(user_input.get()) == answer)  # calling get() here!

entry = tk.Entry(root, textvariable=user_input)
entry.pack()
check = tk.Button(root, text='check 3', command=verify)
check.pack()

root.mainloop()

这篇关于如何从 Entry 小部件获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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