需求:需要在Canvas组件上添加滑块功能
解决:使用tkinter提供的Scrollbar组件,由于没发现直接在画布上显示滑块功能的方法,所以后面采用在显示画布的容器上显示滑块,并绑定到画布上。
具体案例demo:
from tkinter import *
from PIL import ImageTk
from PIL import Image as img
canvas_width =600
canvas_height = 600
root = Tk()
root.geometry("950x650+350+20")
mybox = LabelFrame(root, padx=0, pady=0, width=600, height=600, bg="gray")
canvas = Canvas(mybox, width=canvas_width, height=canvas_height,bg="gray")
scrollbar_y = Scrollbar(mybox, orient=VERTICAL, command=canvas.yview)
scrollbar_x = Scrollbar(mybox, orient=HORIZONTAL, command=canvas.xview)
canvas.config(yscrollcommand=scrollbar_y.set)
scrollbar_y.pack(side="left", fill="y")
canvas.config(xscrollcommand=scrollbar_x.set)
scrollbar_x.pack(side="bottom", fill="x")
canvas.pack(side="left", expand=False)
mybox.pack()
# 在画布上画一张图片
img_open = img.open('./img/4b2aee566471a7e85884f975296e2128.jpeg') # 打开图片
photo = ImageTk.PhotoImage(img_open)
image = canvas.create_image(0, 0, anchor="nw", image=photo)
canvas.configure(scrollregion=canvas.bbox("all"))
# 设置滑块移动位置
canvas.yview_moveto(0.3)
root.mainloop()
效果: