如何使窗口中的滚动条正常工作?

时间:2019-09-03 13:58:54

标签: python tkinter tkinter-canvas

滚动条在那里,鼠标滚轮也被绑定,但是滚动条本身并未按照应有的方式运行。滚动条只是停留在原处,并不实时起作用。应该怎么办?

import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk



def on_window1():

    top = tk.Toplevel()
    top.wm_geometry("794x470")
    top.title('Optimized Map 1')


    frame = tk.Frame(top)
    frame.grid(row=3, column=0)

    canvas1 = tk.Canvas(top, width=400, height=280)
    canvas1.grid(row=0,column=200)

    for i in range(40):
        l3 = tk.Label(canvas1, text="Number of Rectangles:" + str(i))
        canvas1.create_window(50,21*i, window=l3, anchor=tk.NW)

    myscrollbar= tk.Scrollbar(top,orient=tk.VERTICAL,command=canvas1.yview)
    myscrollbar.grid(row=0,column=200, sticky=tk.NS)
    #canvas1.configure(yscrollcommand=myscrollbar.set)
    canvas1.bind_all('<MouseWheel>', lambda event: canvas1.yview_scroll(int(-1*(event.delta/120)), "units"))



    #l4 = tk.Label(canvas1, text="Number of Rectangles:")
    #canvas1.create_window(50,21, window=l4, anchor=tk.NW)

window = tk.Tk()


b1 = tk.Button(window, text="Next", command=on_window1)
b1.grid(row=0, column=0)

window.mainloop()

1 个答案:

答案 0 :(得分:1)

您必须配置画布的scrollregion属性,该属性告诉tkinter使用了多少虚拟画布。通常,它设置为bbox命令返回的 bounding box

bbox命令返回包含一组元素的盒子的坐标。如果将字符串"all"传递给它,它将返回包含画布中所有对象的框的坐标。

将所有内容添加到画布后,添加以下代码行:

canvas1.configure(scrollregion=canvas1.bbox("all"))