我对Python 3中的tkinter有点陌生,我正在尝试创建一个滚动条以与诸如Labels和Radio Buttons之类的许多小部件一起使用。到目前为止,我已经可以使用,但是只有当我将滚动条悬停时才能进行滚动。我希望它可以在窗口中的任何地方工作。
我在Tkinter scroll bar not scrolling中发现了另一条与我有相同问题的帖子,但是尝试解决方案并不能解决我的问题。
这是我要制作的东西的非常模糊的例子
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
scrolly = tk.Scrollbar(root, orient='vertical', command=canvas.yview)
for i in range(60):
label = tk.Label(canvas, text=i)
canvas.create_window(0, 20 * i, window=label)
canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scrolly.set)
canvas.pack(fill='both', expand=True, side='left')
scrolly.pack(fill='y', side='right')
root.mainloop()
我希望能够滚动页面而不必将鼠标悬停在滚动条上
谢谢您的帮助
答案 0 :(得分:3)
def _on_mousewheel(event):
canvas.yview_scroll(int(-1*(event.delta/120)), "units")
canvas.bind_all("<MouseWheel>", _on_mousewheel)
使用鼠标滚轮
https://stackoverflow.com/a/17457843/7590574
另一个想法:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
scrolly = tk.Scrollbar(root, orient='vertical', command=canvas.yview)
pressedY = 0
def mouse_pressed(e, label):
pressedY = e.y
print('p',e, label)
def mouse_released(e, label):
print('r',e, label)
def mouse_motion(e, label):
m = pressedY - e.y
# print('m',e, label)
canvas.yview_scroll(int(-1*(m/50)), "units")
labelList = []
for i in range(60):
labelList.append(tk.Label(canvas, text=i))
canvas.create_window(0, 20 * i, window=labelList[i])
labelList[i].bind("<Button-1>",lambda e,i=i:mouse_pressed(e, labelList[i]))
labelList[i].bind("<ButtonRelease-1>",lambda e,i=i:mouse_released(e, labelList[i]))
labelList[i].bind("<B1-Motion>",lambda e,i=i:mouse_motion(e, labelList[i]))
canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scrolly.set)
canvas.pack(fill='both', expand=True, side='left')
scrolly.pack(fill='y', side='right')
root.mainloop()