我正在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 了几种不同的配置,但我无法解决它.观察两个函数中的变量将返回正确的结果.任何帮助和指导都是非常感谢的,对我如何编写代码的建设性批评也是非常感谢的