Home > Blockchain >  why is the variable undefined
why is the variable undefined

Time:06-14

import tkinter as tk
from tkinter import *
import os

root = Tk()
root.geometry('700x700')

For example, the user enters the path of the chrome.exe but it says it is undefined, maybe because it is in the root.mainloop, I have tried to put it outside of the mainloop but same result

def exeNew():
        Path = text0.get(1.0, "end-1c")


text0 = tk.Text(root, height=1, width=30)
text0.place(x=400, y=500)

printButton = tk.Button(root, text="ADD", command=exeNew)
printButton.place(x=460, y=640)

Then here os.startfile should open chrome.exe

os.startfile(Path)

root.mainloop()

Error Output

CodePudding user response:

You variable Path is only defined inside the function. You cannot access to it from outside the function.

It same as

def declare_variable():
    x = 5
print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

One solution would be to declare Path before creating the button

CodePudding user response:

the function exeNew is setting a local variable Path which then no longer exists after exiting the scope of exeNew.

In exeNew, insert the line global Path before setting Path.

you may want to consider explicitly setting Path to None at the start of the program and only call os.startfile if Path is not None.

CodePudding user response:

I think declaring the variable Path as global will be needed.

In more detail global variables,are variables that are accessible globally, or everywhere throughout the program. Once declared, they remain in memory throughout the runtime of the program. This means that they can be changed by any function at any point and may affect the program as a whole.

  • Related