我对Python还很陌生,所以如果我的问题微不足道甚至很愚蠢,我很抱歉。我试图建立一个小模块,对一个按钮的回调反应(这不是在代码中)。回调在main()函数中模拟。现在我的问题是,我不知道如何摆脱全局名称错误。它说drink0_ingred没有被定义为全局名称。我需要这个作为self。10标签的文本。这是我目前所看到的:
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作为全局名称,并使其可访问其他函数?谢谢你的帮助!
你可以做两件事:
全球化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