Question

I am still pretty new to Python, so I'm sorry if my question is trivial or even stupid. I am trying to build a little module that reacts on a callback of a Button (which isn't in the code). The callback is simulated in the main()-function. Now my problem is that I can't figure out how to get rid of the global name error. It says that drink0_ingred is not defined as global name. I need this as text for the label called self.l0. This is what I have so far:

import tkinter
from tkinter import ttk


def main():
    root = tkinter.Tk()
    callback = callbackkb0()
    drink0 = Drink0(root)
    root.mainloop()


def callbackkb0():
    with open(file="drink0_ingred.txt") as ingred0:
        drink0_ingred = ingred0.read()
    print(drink0_ingred)
    return drink0_ingred



class Drink0(ttk.Frame):
    def __init__(self, root):
        ttk.Frame.__init__(self, root)
        self.grid()
        self.widgets_create()

    def widgets_create(self):
        self.l0 = ttk.Label(self, text=drink0_ingred)
        self.l0.grid()


main()

How do I define drink0_ingred as global name and make it accessable for other functions? Thanks for helping me!

Was it helpful?

Solution

Two things you can do:

Globalise drink0_ingred:

with open(file="drink0_ingred.txt") as ingred0:
    global drink0_ingred
    drink0_ingred = ingred0.read()

Call the function instead of calling the variable:

self.l0 = ttk.Label(self, text=callbackkb0()) # Notice how I called the function 
                                              # because it returned drink0_ingred
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top