两个 tkinter 滚动条冲突:第一个滚动条正确,第二个滚动条不正确

问题描述 投票:0回答:1

我有一个 tabcontrol,其中 Tab 2.1 和 Tab 2.2 的滚动条发生冲突。

Tab 2.2
滚动条垂直滚动正确。但是,
Tab 2.1
的滚动条不滚动。

我该如何解决这个问题?

from tkinter import ttk
import tkinter as tk

window = tk.Tk() 
window.attributes('-zoomed', True)

style = ttk.Style(window)

tabControl = ttk.Notebook(window, style='Custom.TNotebook', width=700, height=320)
tabControl.place(x=1, y=1)

#TAB 1
main = ttk.Notebook(tabControl)
tabControl.add(main, text ='Tab 1')

#TAB 2
tab2 = ttk.Notebook(main)
main.add(tab2, text="Tab 2")

##TAB 2.1
a = ttk.Frame(tab2)
tab2.add(a, text="Tab 2.1")

canvas = tk.Canvas(a)

scrollbar = ttk.Scrollbar(a, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas, width = 800, height = 800)

scrollable_frame.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)

combo1=ttk.Combobox(scrollable_frame, width = 18)
combo1.place(x=20, y=20)
combo1['value'] = ["text1", "text2"]

canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

##TAB 2.2
b = ttk.Frame(tab2)
tab2.add(b, text="Tab 2.2")

canvas = tk.Canvas(b)

scrollbar = ttk.Scrollbar(b, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas, width = 800, height = 800)

scrollable_frame.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)

combo1=ttk.Combobox(scrollable_frame, width = 18)
combo1.place(x=20, y=20)
combo1['value'] = ["text1", "text2"]


canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

window.mainloop()
python python-3.x tkinter canvas scrollbar
1个回答
0
投票

由于您对两个画布使用了相同的变量

canvas
,因此两个绑定回调中的
canvas
将引用最后一个(在选项卡2.2内)。

您可以使用

e.widget.master
在两个绑定回调中引用正确的 canvas

scrollable_frame.bind(
    "<Configure>",
    lambda e: e.widget.master.configure(
        scrollregion=e.widget.master.bbox("all")
    )
)

请注意,

e.widget
指的是
scrollable_frame
触发事件,因此
e.widget.master
指的是
scrollable_frame
的父级,即画布。

或者简单地为两个画布使用不同的变量名称。

© www.soinside.com 2019 - 2024. All rights reserved.