Tkinter事件处理程序无法看到全局变量

时间:2019-07-16 23:43:05

标签: python tkinter

无论何时为我的按钮调用on_click事件处理程序,其方法都不会确认我的全局变量的存在。

是什么原因引起的?如何/如何在事件处理程序中访问全局变量?

我已经尝试过将全局变量的值传递给方法,

from pynput.mouse import Button, Controller
from pynput import mouse

import tkinter as tk
import sys

controller = Controller()
recordings = []
is_recording = False
listener = None
top = tk.Tk()


class Recording:
    def __init__(self):
        self.actions = []
        self.key_bind_code = -1

    def add_action(self):
        self.actions.append(controller.position)

    def play(self):
        for action in actions:
            do_action(action)


def on_click(recording):
    recording.add_action()

def start_recording():
    r = Recording()
    recordings.append(r)
    listener = mouse.Listener(on_click=on_click(r))
    listener.start()

def stop_recording():
    listener.stop()

def handle_recording():
    print("Recording: " + str(is_recording))
    if is_recording:
        stop_recording()
        is_recording = False
    else:
        start_recording()
        is_recording = True


button = tk.Button(top, text="Record", command=handle_recording)
button.pack()

top.mainloop()

调用处理程序时,这是我收到的消息。

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\pdiddy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "repeat.py", line 60, in handle_recording
    print("Recording: " + str(is_recording))
UnboundLocalError: local variable 'is_recording' referenced before assignment

1 个答案:

答案 0 :(得分:2)

要使is_recordinghandle_recording()函数中不被视为局部变量,必须通过在函数的开头添加global is_recording语句来声明它不是一个局部变量。像这样:

def handle_recording():
    global is_recording  # ADD THIS LINE.
    print("Recording: " + str(is_recording))
    if is_recording:
        stop_recording()
        is_recording = False
    else:
        start_recording()
        is_recording = True

虽然可以读取,但尚未声明global的现有全局变量的值(由于Python查找值的方式),可以更改 >一个值,但是,您必须将其显式声明为global。按照惯例,推荐的操作位置是在对其进行操作的代码块(此处的功能)的开头。