I have this function here.
def choose_file():
file = askopenfile(mode ='r', filetypes =[('xodr Files', '*.xodr')])
if file:
res = "selected:", file
else:
res = "file not selected"
return(res)
I have this button to open the dialog and choose a file
e3=Button (scalF, text='Wählen Sie ein Dokument',font=('Bahnschrift SemiLight',12),command=choose_file, bg='blue')
e3.pack(side='top')
after choosing a file and closing the dialog I want to display the value of the variable defined res in the choose_file() in the label below
chosenFile = Label(scalF,text="I want to write here",font=('Bahnschrift SemiLight', 10))
chosenFile.pack(side='top')
can you explain how to read the variable resfrom the global scope?
CodePudding user response:
You can use tk.StringVar to hold the strings variables.
file_result = tk.StringVar()
def choose_file():
file = askopenfile(mode ='r', filetypes =[('xodr Files', '*.xodr')])
if file:
res = "selected: {0}".format(file.name)
else:
res = "file not selected"
file_result.set(res)
Then this variable(file_result) can be passed to Labels textvariable argument(Whose value will be used in place of the text).
chosenFile = Label(scalF, font=('Bahnschrift SemiLight', 10), textvariable=file_result)
CodePudding user response:
one of the ways i can recommend is :
add global res to the 1st line of ur function.
CodePudding user response:
You can use the variable in the global scope by declaring it using the global keyword.
def choose_file():
global res
file = askopenfile(mode ='r', filetypes =[('xodr Files', '*.xodr')])
if file:
res = "selected:", file
else:
res = "file not selected"
return(res)
If you wanna explore more, you can learn about namespaces in python
CodePudding user response:
You could use a class:
class File():
def __init__(self):
self.res = None
e3=Button (scalF, text='Wählen Sie ein Dokument', font=('Bahnschrift SemiLight',12), command=self.choose_file, bg='blue')
e3.pack(side='top')
def choose_file(self):
# Your implementation but updating self.res, without return
def get_res(self):
return self.res
