全局变量的使用方法

how to use global variable

我是 python 的新手,我需要一些关于声明全局小部件标签的帮助。

def leftClick(event):
    global label1

    #the event is called when the 'leftClick' function is used
    #thus, displaying the color of the font

    label1=Label(text=event.widget.cget("fg"),bg=event.widget.cget("fg"))
    label1.grid(row=0, column=0,sticky=S)

def rightClick(event):
    global label1
    #same goes for 'rightClick' def function but it displays the background of the buttons

    label1=Label(text=event.widget.cget("bg"),bg=event.widget.cget("bg"))
    label1.grid(row=0, column=0,sticky=S)

    #since its outside the class, we refer to widgets inside the class with event.widget

'label1' 未在全局范围内定义

问题是您指出 label1 存在于全局级别(在函数之外),但实际上从未在那里声明过。

这只是一个警告,但要删除它,请在函数上方(外部)添加 label1 = None

label1 = None
def leftClick(event):
    global label1  # no warning
    ......