Python 更改Tkinter条目';单击按钮时显示文本
需要实现的功能是:单击Tkinter按钮时,条目的文本将发生更改。下面是代码片段:Python 更改Tkinter条目';单击按钮时显示文本,python,tkinter,Python,Tkinter,需要实现的功能是:单击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, t
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\u条目需要声明为全局。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()
如何导入Tkinter?我假设这不是模块级别的代码,否则,
path\u entry
在全局范围内定义得非常清楚,您拥有的代码将正常工作。请在上下文中显示代码段。当我运行您的代码时,我得到的名称“tk”未定义
,而不是全局名称“path\u entry”未定义
。请提供一个例子来说明您的问题。@Kevin使用tkinter的一个常见惯例是将tkinter作为tk导入,这样您就不必使用使名称空间混乱的import*
,而不必每次使用它时都使用全名tkinter
。我知道,但OP在他的代码中没有这样做,所以我不能运行它。