来自函数的tkinter入口变量 [英] tkinter entry variable from function
问题描述
这应该很容易,但是我在寻找所需答案时感到疲倦.下面的代码弹出一个输入窗口.我在输入字段中输入内容,函数show_entry_fields()获取输入内容,然后窗口关闭.然后,我想在下面的代码中使用新的输入变量,但它们会恢复为初始的全局值.我将它们定义为全局,因此我可以在整个脚本中使用它们,但是entry函数无法更改它们.如何从用户那里获得输入,然后该程序的其余部分可以使用该输入?
This should be easy but I am suffering search fatigue for the answer I need. The code below pops up an input window. I make entries into the entry fields and the function show_entry_fields() gets the input and the window closes. I then want to use the new entry variables in code that follows but they revert back to their initial, global values. I define them as global so I can use them throughout the script, but the entry function fails to change them. How can I get input from users that is then available to the rest of the program?
import tkinter as tk
site = 'cats'
score = 100
def show_entry_fields():
site = e1.get()
score = e2.get()
master.destroy()
#print(site,score)
master = tk.Tk()
master.columnconfigure(1, weight=1)
tk.Label(master, text="website").grid(row=0)
tk.Label(master, text="Image Ranking").grid(row=1)
e1 = tk.Entry(master)
e2 = tk.Entry(master)
e1.insert(0,site)
e1.grid(row=0, column=1, sticky='EW')
e2.grid(row=1, column=1, sticky='EW')
tk.Button(master, text='Quit', command=master.quit).grid(row=3, column=0, sticky='W', pady=4)
tk.Button(master, text='Go!', command=show_entry_fields).grid(row=3, column=1, sticky='W', pady=4)
master.mainloop( )
print(site, score)
推荐答案
这是否解决了问题?
def show_entry_fields():
global site, score, master
site = e1.get()
score = e2.get()
master.destroy()
至少程序结尾处的打印内容正在打印正确的答案.
At least the print at the end of the program is printing the right answer.
这篇关于来自函数的tkinter入口变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!