为什么我的 Tkinter 滚动条会填满窗口的整个长度?
我有工作水平滚动条,但由于某种原因它不会调整“可见”栏的大小。它确实可以完美滚动,但在添加样式 clam
之前我什至没有注意到有一个栏。
这是我的代码:
from tkinter import *
from tkinter import ttk
root = Tk()
style = ttk.Style()
style.theme_use('clam')
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
my_canvas = Canvas(main_frame)
my_canvas.pack(side=TOP, fill=BOTH, expand=1)
my_scrollbar = ttk.Scrollbar(main_frame, orient=HORIZONTAL, command=my_canvas.xview)
my_scrollbar.pack(side=BOTTOM, fill=X)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all")))
seccond_frame = Frame(my_canvas)
my_canvas.create_window((0,0), window=seccond_frame, anchor="nw")
for i in range(100):
Label(seccond_frame, text=f"a{i}").grid(row=0, column=i)
root.update()
root.mainloop()
I have working horizontal scrollbar, but for some reason it does not rezise the "visible" bar. It does scroll perfectly, but I even didin't notice there was a bar before I added style clam
.
Here is my code:
from tkinter import *
from tkinter import ttk
root = Tk()
style = ttk.Style()
style.theme_use('clam')
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
my_canvas = Canvas(main_frame)
my_canvas.pack(side=TOP, fill=BOTH, expand=1)
my_scrollbar = ttk.Scrollbar(main_frame, orient=HORIZONTAL, command=my_canvas.xview)
my_scrollbar.pack(side=BOTTOM, fill=X)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion=my_canvas.bbox("all")))
seccond_frame = Frame(my_canvas)
my_canvas.create_window((0,0), window=seccond_frame, anchor="nw")
for i in range(100):
Label(seccond_frame, text=f"a{i}").grid(row=0, column=i)
root.update()
root.mainloop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码中有两个问题:
my_canvas.configure(yscrollcommand=my_scrollbar.set)
应该是my_canvas.configure(xscrollcommand=my_scrollbar.set)
向
seccond_frame
,它是seccond_frame
调整大小,而不是my_canvas
。因此,您需要在seccond_frame
上绑定
而不是my_canvas
There are two issues in your code:
my_canvas.configure(yscrollcommand=my_scrollbar.set)
should bemy_canvas.configure(xscrollcommand=my_scrollbar.set)
when adding items to
seccond_frame
, it isseccond_frame
get resized, notmy_canvas
. So you need to bind<Configure>
onseccond_frame
instead ofmy_canvas