I tried running this code and it just crashes, giving me the error (NameError: name 'coordenadas' is not defined). I need to be able to work with that in the future, therefor printing right away, eventho it solves the code, it doesn't solve my problem.
from tkinter import *
ronda = 0
root = Tk()
root.title("Batalha Naval")
root.eval('tk::PlaceWindow . center') #põe a cena no centro
root.geometry('{}x{}'.format(500, 200)) #muda tamanho da janela
root.attributes('-topmost',1) #põe na à frente de todas as janelas sempre
tentativa = Label(root, text="Esta é a tua {}º tentativa".format(ronda))
instruçoes = Label(root, text="Introduz as cordenadas:")
entrada = Entry(root, width=50, borderwidth=5)
def click():
global coordenadas
coordenadas = int(entrada.get())
root.destroy()
print(coordenadas)
botao = Button(root, width=10, height=2, text="Confirmar", bg='red', command=click)
tentativa.pack()
instruçoes.pack()
entrada.pack()
botao.pack()
print(coordenadas)
mainloop()
if I try to print it inside the defining the function it runs, but I'll need to work with that input later on so it mustn't be only working inside that def.
I've tried to see if it's global by removing the print(coordenadas)
and putting print(globals())
and then it printed the input I did in the button
I tried also after deleting that part to run this `
if coordenadas in locals(): print("It's local") #Replace 'variable' with the variable
elif coordenadas in globals(): print("It's global") #But keep the quotation marks
else: print("It's not defined")
and it says again NameError: name 'coordenadas' is not defined
CodePudding user response:
Here 'coordenadas' won't be defined until you press the button 'botao'. Before you have the chance to press the button, the print under 'botao.pack()' will try to access the variable coordenadas which is not defined yet; this will raise the NameError.
If you need to access coordenadas on the global scope, I will suggest you to define the variable outside the function even if it's assigning a 0 to it.