需要实现的功能是:单击Tkinter按钮时,会更改条目的文本。这是代码片段:
import Tkinter as tk
def create_heatmap_button_callback():
path_entry.delete(0, tk.END)
path_entry.insert(0, "clicked!")
def main():
root = tk.Tk()
path_entry = tk.Entry(master = root, text = "not clicked")
path_entry.grid(row=1, column=0, sticky = tk.W)
create_heatmap_button = tk.Button(master = root, text = "create map", command = create_heatmap_button_callback)
create_heatmap_button.grid(row=2,column=0,sticky = tk.W)
tk.mainloop()
if __name__ == "__main__":
global path_entry
main()
当点击按钮时,这是输出:
NameError:未定义全局名称“path_entry”
这样做的正确方法是什么?
答案 0 :(得分:1)
我可能发现错误,path_entry需要声明为global.Python的全局变量的行为与其他语言不同。
import Tkinter as tk
def create_heatmap_button_callback():
#global path_entry
path_entry.delete(0, tk.END)
path_entry.insert(0, "clicked!")
def main():
root = tk.Tk()
global path_entry
path_entry = tk.Entry(master = root, text = "not clicked")
path_entry.grid(row=1, column=0, sticky = tk.W)
create_heatmap_button = tk.Button(master = root, text = "create map", command = create_heatmap_button_callback)
create_heatmap_button.grid(row=2,column=0,sticky = tk.W)
tk.mainloop()
if __name__ == "__main__":
main()