简体   繁体   English

Python tkinter 如何从输入框中获取值

[英]Python tkinter how to get value from an entry box

I am trying to make a little thing in python like JOpenframe is java and I'm trying to make an entry box.我正在尝试在 python 中做一些小事,比如 JOpenframe 是 java 并且我正在尝试制作一个输入框。 That works fine but when I try to get the value and assign it to variable "t" nothing works.这很好,但是当我尝试获取值并将其分配给变量“t”时,没有任何效果。 This is what I have:这就是我所拥有的:

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

I've tried to make "g" a global variable but that doesn't work.我试图使“g”成为全局变量,但这不起作用。 I have no idea how to get the value from this, and I'm hoping someone who does can help me out.我不知道如何从中获得价值,我希望有人能帮助我。 Thanks!谢谢!

If you want to return the value of the entry box after ButtonBox() exits, you need to:如果要在ButtonBox()退出后返回输入框的值,需要:

  • initialize g inside ButtonBox()ButtonBox()中初始化g
  • declare g as nonlocal variable inside inner function Stop()g声明为内部 function Stop()内的nonlocal变量
  • call g = e.get() before destroying the window在销毁 window 之前调用g = e.get()

Below is the modified code:下面是修改后的代码:

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)

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

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