PYTHON 我不能在标题中填入整个问题,所以在这里是
我正在尝试制作一个tkinter框来接受输入并在接受输入后关闭,这可以通过root.destroy()命令简单地完成,但这不是问题。我试图在整个代码中都可以访问(用户提供的)输入。每当我尝试使用return语句时,它就不会被注意到,因为root.destroy()在它之前命令了它。反之亦然。
from tkinter import *
score = 0
root = Tk()
nameLabel = Label(root, text="Name")
ent = Entry(root, bd=5)
def getName():
global score
entt= (ent.get())
score = 1
root.destroy()
return entt
b1 = Button(root, text='FirstC', command=getName)
b1.pack(side=LEFT, padx=5, pady=15)
nameLabel.pack()
ent.pack()
root.mainloop()
print(func1())
错误
Traceback (most recent call last):
File "C:\Users\14753\OneDrive\Desktop\Stocks\trying.py", line 21, in <module>
print(getName())
File "C:\Users\14753\OneDrive\Desktop\Stocks\trying.py", line 9, in getName
entt= (ent.get())
File "C:\Users\14753\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2682, in get
return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".!entry"
我一直在解决这个问题已有一段时间了,任何帮助都将非常有帮助!
答案 0 :(得分:2)
Button
运行函数,但是它没有获取返回值的方法。在函数中,您必须将Entry
中的文本分配给全局变量,然后在函数外部使用此变量。
import tkinter as tk
# --- functions ---
def get_name():
global name # inform function to use global variable instead of creating local one
name = name_entry.get() # assign text to global variable
root.destroy()
# --- main ---
name = '' # global variable with default value (if you don't put name)
root = tk.Tk()
name_label = tk.Label(root, text='Name')
name_label.pack()
name_entry = tk.Entry(root)
name_entry.pack(side='right')
b = tk.Button(root, text='First', command=get_name)
b.pack(side='left')
root.mainloop()
print('name:', name) # display text from global variable