【问题标题】:Python tkinter how to get value from an entry boxPython tkinter如何从输入框中获取值
【发布时间】:2022-09-27 08:59:46
【问题描述】:

我正在尝试在 python 中做一些小事情,比如 JOpenframe 是 java,我正在尝试制作一个输入框。这很好,但是当我尝试获取值并将其分配给变量 \"t\" 时,没有任何效果。这就是我所拥有的:

def ButtonBox(text):
    root = Tk()
    root.geometry(\"300x150\")
    t = Label(root, text = text, font = (\"Times New Roman\", 14))
    t.pack()
    e = Entry(root, borderwidth = 5, width = 50)
    e.pack()
    def Stop():
        root.destroy()
        g = e.get()
    ok = Button(root, text = \"OK\", command = Stop)
    ok.pack()
    root.mainloop()
t = ButtonBox(\"f\")

我尝试将“g”设为全局变量,但这不起作用。我不知道如何从中获得价值,我希望有人能帮助我。谢谢!

  • 您无法从已销毁的条目小部件中获取值,因为您在调用 e.get() 之前已经销毁了根窗口。此外,还不清楚您想要变量 g 上的内容。是否要返回该值,即将其分配给变量t
  • @acw1668 是的,我想将值分配给 var t

标签: python tkinter


【解决方案1】:

如果想在ButtonBox()退出后返回输入框的值,需要:

  • ButtonBox() 内部初始化g
  • g 声明为nonlocal 内部函数内的变量Stop()
  • 在销毁窗口之前调用g = e.get()

下面是修改后的代码:

from tkinter import *

def ButtonBox(text):
    g = ""   # initialize g
    root = Tk()
    root.geometry("300x150")
    t = Label(root, text = text, font = ("Times New Roman", 14))
    t.pack()
    e = Entry(root, borderwidth = 5, width = 50)
    e.pack()
    def Stop():
        # declare g as nonlocal variable
        nonlocal g
        # get the value of the entry box before destroying window
        g = e.get()
        root.destroy()
    ok = Button(root, text = "OK", command = Stop)
    ok.pack()
    root.mainloop()
    # return the value of the entry box
    return g
t = ButtonBox("f")
print(t)

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多