0

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?

4 Answers 4

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It works. Thanks!! @Abdul Niyas P M just one question: i don't have my function choose_file() inside the root = Tk() so i moved file_result = tk.StringVar() under root = Tk(). is that the best thing to do or should i move the function under the root = Tk() as well?
0

one of the ways i can recommend is : add global res to the 1st line of ur function.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.