0

我对 Python 还是很陌生,所以如果我的问题是微不足道的甚至是愚蠢的,我很抱歉。我正在尝试构建一个对 Button 回调(不在代码中)做出反应的小模块。回调在 main() 函数中模拟。现在我的问题是我无法弄清楚如何摆脱全局名称错误。它说drink0_ingred 没有定义为全局名称。我需要它作为名为 self.l0 的标签的文本。这是我到目前为止所拥有的:

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()

如何将drink0_ingred 定义为全局名称并使其可用于其他功能?谢谢你帮助我!

4

1 回答 1

1

你可以做两件事:

全球化drink0_ingred

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

调用函数而不是调用变量:

self.l0 = ttk.Label(self, text=callbackkb0()) # Notice how I called the function 
                                              # because it returned drink0_ingred
于 2013-04-23T13:47:34.660 回答