python - Tkinter 事件处理程序无法查看全局变量

标签 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

最佳答案

要使 is_recording 不被视为 handle_recording() 函数中的局部变量,您必须通过添加 全局 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 查找值的方式),以更改但是,您必须将其显式声明为全局值。按照惯例,建议执行此操作的位置是在其被操作的代码块的最开头(此处的函数)。

关于python - Tkinter 事件处理程序无法查看全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066768/

相关文章:

python:我需要在文本框中插入一个文本框

python - 将 3d sigmoid 拟合到数据

python - 是否可以在 matplotlib hexbin 图上绘制相同点的列表?

python - “CityListViewSet”应包含 `serializer_class` 属性,或覆盖 `get_serializer_class()` 方法

python - 如何将 python 多处理进程输出发送到 Tkinter gui

python - 在 py2exe 中复制图像和数据文件不起作用?

python - 名称为 "calculated"的类属性

python - 用于 Python3 的 OSX HIDAPI 安装(pip3 故障排除): High-Sierra

python - 为什么这两行代码不会产生相同的结果?

python - Tkinter - 窗口焦点丢失事件