我正在try 为Python3中的tkinter制作一个定制的滚动条小部件.我正在使用类和函数来组织代码.我有一个布尔变量,程序的其余部分需要访问它来确定滚动条是否处于活动状态,以便它可以通过用户的鼠标进行可视更新.更改此变量是在两个函数中完成的,但是,当我观察到它已更新的函数外部的变量时,这让我认为我在处理自身的方式上做了一些错误,或者只是全局变量和局部变量在函数和类中的工作方式.我试了很多方法,但都不能让它起作用.

以下是更改变量的两个函数:

def scrollOn(self):
    self.scrolling = True
def scrollOff(self):
    self.scrolling = False

这两个函数都是由tkintertkinter绑定事件触发的.按钮:

scrollBar = tk.Button(window, bg = "#000000")
scrollBar.place(x = 390, y = 30, width = 20, height = 40)
scrollBar.bind("<Button-1>", lambda s = self : scrollOn(s))
scrollBar.bind("<ButtonRelease-1>", lambda s = self : scrollOff(s))

以下是所有代码:

import tkinter as tk

class scrollbar:

    scrolling = False   

    def __init__(self, window):

        scrollFrame = tk.Frame(window, bg = "#666666")
        scrollFrame.place(x = 10, y = 10, width = 400, height = 400)

        scrollBounds = tk.Frame(window, bg = "#444444")
        scrollBounds.place(x = 390, y = 30, width = 20, height = 360)

        upButton = tk.Button(window, text = "")
        upButton.place(x = 390, y = 10, width = 20, height = 20)

        downButton = tk.Button(window, text = "")
        downButton.place(x = 390, y = 390, width = 20, height = 20)

        def scrollOn(self):
            self.scrolling = True
        def scrollOff(self):
            self.scrolling = False
            
        scrollBar = tk.Button(window, bg = "#000000")
        scrollBar.place(x = 390, y = 30, width = 20, height = 40)
        scrollBar.bind("<Button-1>", lambda s = self : scrollOn(s))
        scrollBar.bind("<ButtonRelease-1>", lambda s = self : scrollOff(s))

        def updateScrollbar(self):
            if self.scrolling == True:
                print("SCROLLING")
            window.after(1, lambda s = self : updateScrollbar(s))
            
        window.after(1, lambda s = self : updateScrollbar(s))

当我试图解决这个问题时,我try 了几种不同的配置,但我无法解决它.观察两个函数中的变量将返回正确的结果.任何帮助和指导都是非常感谢的,对我如何编写代码的建设性批评也是非常感谢的

推荐答案

scrollOff中不是scrollbar,而是ButtonPress event.删除该参数或将其更改为其他参数

def scrollOn():
    self.scrolling = True

def scrollOff():
    self.scrolling = False

scrollBar = tk.Button(window, bg="#000000")
scrollBar.place(x=390, y=30, width=20, height=40)
scrollBar.bind("<Button-1>", lambda s=self: scrollOn())
scrollBar.bind("<ButtonRelease-1>", lambda s=self: scrollOff())

Python相关问答推荐

如何在Pandas 中存储二进制数?

ValueRight:参数目标和输出必须具有相同的形状.接收:目标.形状=(无,512),输出.形状=(无,3)

保留包含pandas pandras中文本的列

使用Python Great Expectations和python-oracledb

Flask主机持续 bootstrap 本地IP| Python

在Transformer中使用LabelEncoding的ML模型管道

查找下一个值=实际值加上使用极点的50%

有什么方法可以避免使用许多if陈述

比较两个二元组列表,NP.isin

Select 用a和i标签包裹的复选框?

在Python Attrs包中,如何在field_Transformer函数中添加字段?

在Pandas DataFrame操作中用链接替换'方法的更有效方法

Telethon加入私有频道

Python—从np.array中 Select 复杂的列子集

为什么抓取的HTML与浏览器判断的元素不同?

ThreadPoolExecutor和单个线程的超时

使用特定值作为引用替换数据框行上的值

如何在达到end_time时自动将状态字段从1更改为0

替换现有列名中的字符,而不创建新列

使用Openpyxl从Excel中的折线图更改图表样式