Tkinter,Canvas在调整窗口大小时拒绝扩展或收缩

时间:2014-10-18 01:05:54

标签: python canvas tkinter

我试图让我的画布根据窗口大小进行扩展和收缩,并根据需要使用滚动条。我还没有添加水平滚动条,但它既不水平也不垂直,而是固定地保持任意大小。

我有两个框架的原因是因为内部框架水平滚动,因为我有几个必须一起滚动的画布,其中只有一个也垂直滚动。

root = Tk()
maxtick = 1000

frame = ttk.Frame(root)     # , padding="3 3 12 12")
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)

inner_frame = ttk.Frame(frame)
inner_frame.grid(column=0, row=0, sticky=(N, W, E, S))
inner_frame.columnconfigure(0, weight=1)
inner_frame.rowconfigure(0, weight=1)

# Primary canvas (inner_frame)
canvas = Canvas(inner_frame, bg='#FFF', width=maxtick,
                scrollregion=(0, 0, maxtick, 16 * (128 + 1 + 1)) )
canvas.grid(column=0, row=0, sticky=(N, W, E, S))

for y in range(1, 128 + 1 + 1):
    canvas.create_line(0, 16 * y - 1, maxtick, 16 * y - 1)

# Vertical scrollbar
vbar = ttk.Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
vbar.grid(column=1, row=0, sticky=(N, W, E, S))
canvas.configure(yscrollcommand=vbar.set)

# canvas.create_line(10, 10, 200, 50)

root.mainloop()

1 个答案:

答案 0 :(得分:3)

您还需要配置最外层的网格布局。

...
root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
...

顺便说一句,如何将packexpand=1, fill=BOTH一起使用。

root = Tk()
frame = ttk.Frame(root)
frame.pack(expand=1, fill=BOTH)

maxtick = 1000

inner_frame = ttk.Frame(frame)
inner_frame.pack(expand=1, fill=BOTH, side=LEFT)

# Primary canvas (inner_frame)
canvas = Canvas(inner_frame, bg='#FFF', width=maxtick,
                scrollregion=(0, 0, maxtick, 16 * (128 + 1 + 1)) )
canvas.pack(expand=1, fill=BOTH)

for y in range(1, 128 + 1 + 1):
    canvas.create_line(0, 16 * y - 1, maxtick, 16 * y - 1)

# Vertical scrollbar
vbar = ttk.Scrollbar(frame, orient=VERTICAL, command=canvas.yview)
vbar.pack(fill=Y, side=LEFT)
canvas.configure(yscrollcommand=vbar.set)

root.mainloop()