[英]Python tkinter how to get value from an entry box
我正在嘗試在 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”成為全局變量,但這不起作用。 我不知道如何從中獲得價值,我希望有人能幫助我。 謝謝!
如果要在ButtonBox()
退出后返回輸入框的值,需要:
ButtonBox()
中初始化g
g
聲明為內部 function Stop()
內的nonlocal
變量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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.