-3

The function need to be realized is: when the Tkinter button is clicked, an entry's text is changed. Here's the code snippet:

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() 

and when clicked the button, here's the output:

NameError: global name 'path_entry' is not defined

What is the correct way to do this?

Dracarys
  • 291
  • 1
  • 11
  • How are you importing Tkinter? – Andrew Li Jun 17 '16 at 13:49
  • 1
    I'm assuming this is not the code at module level, otherwise `path_entry` is very clearly defined globally and the code you have would work correctly. Please show the code snippet in context. – Tadhg McDonald-Jensen Jun 17 '16 at 14:01
  • 1
    When I run your code, I get `name 'tk' is not defined`, not `global name 'path_entry' is not defined`. Please provide a [mcve] that demonstrates your problem. – Kevin Jun 17 '16 at 14:03
  • @Kevin one common convention for using tkinter is to do `import tkinter as tk`, that way you don't use the `import *` that clutters the namespace but don't need to use the full name `tkinter` everytime you use it. – Tadhg McDonald-Jensen Jun 17 '16 at 14:07
  • I know, but OP didn't do that in his code, so I can't run it. – Kevin Jun 17 '16 at 14:08
  • are you familiar with the differences between local and global variables? – Bryan Oakley Jun 17 '16 at 15:31
  • Hi all, thanks for your suggestion, I've edited the code to make it work before click the button. Hi @BryanOakley, I added one line to make it global (I think so...), but it seems not work. – Dracarys Jun 17 '16 at 15:52

1 Answers1

1

I've possibly found the error, the path_entry need to be declared as global.Python's global variable's behavior is different from other languages.

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() 
Dracarys
  • 291
  • 1
  • 11