经过几次测试和得到的帮助,我设法得到了一个有几个复选框的滚动条的代码。我目前的问题是滚动条比它需要的空间大得多,通常我不能根据自己的喜好改变它的大小。这是我的代码:
import tkinter as tk
class CheckboxList(tk.Frame):
def __init__(self, master=None, **kw):
super().__init__(master, **kw)
self.checkbuttons = []
self.vars = []
self.canvas = tk.Canvas(self, bg='white', bd=0, highlightthickness=0)
self.yscroll = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.frame = tk.Frame(self.canvas)
self.canvas.create_window((0, 0), window=self.frame, anchor='nw')
self.canvas.configure(yscrollcommand=self.yscroll.set)
self.canvas.grid(row=0,column=0, sticky='nsew')
self.yscroll.grid(row=0, column=1, sticky='nse')
for i in range(20):
var = tk.IntVar(value=0)
cb = tk.Checkbutton(self.frame, text=f"checkbutton #{i}", variable=var, onvalue=1, offvalue=0)
cb.grid(row=i, column=0, sticky='w')
self.checkbuttons.append(cb)
self.vars.append(var)
self.frame.update_idletasks()
self.canvas.config(scrollregion=self.canvas.bbox("all"))
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _on_mousewheel(self, event):
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
root = tk.Tk()
cl = CheckboxList(root, width=20, height=10)
cl.grid(row=0,column=0,sticky='nsew')
root.mainloop()
我已经做了几个测试,改变“网格”的值,但我不能。我希望我可以有更多的控制大小。正如你可以看到,从图像中,有很多白色,我希望能够改变整体高度以及
编辑:实际代码:
class CheckboxList(tk.Frame):
def __init__(self, master=None, **kw):
super().__init__(master, **kw)
self.checkbuttons = []
self.vars = []
self.canvas = tk.Canvas(self, bg='white', bd=0, highlightthickness=0)
#self.canvas = tk.Canvas(self, bg='white', bd=0,width=115, highlightthickness=0)
self.yscroll = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.frame = tk.Frame(self.canvas)
self.canvas.create_window((0, 0), window=self.frame, anchor='nw')
self.canvas.configure(yscrollcommand=self.yscroll.set)
self.canvas.grid(row=0,column=0, sticky='nsew')
self.yscroll.grid(row=0, column=1, sticky='nse')
for i in range(20):
var = tk.IntVar(value=0)
cb = tk.Checkbutton(self.frame, text=f"checkbutton #{i}", variable=var, onvalue=1, offvalue=0)
cb.grid(row=i, column=0, sticky='w')
self.checkbuttons.append(cb)
self.vars.append(var)
self.frame.update_idletasks()
#self.canvas.config(scrollregion=self.canvas.bbox("all"))
self.frame.bind("<Configure>", lambda e: self.canvas.config(width=e.width, scrollregion=self.canvas.bbox("all")))
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _on_mousewheel(self, event):
self.canvas.yview_scroll(int(-1*(event.delta/120)), "units")
2条答案
按热度按时间kcugc4gi1#
在第8行添加
width
。更改此内容:
致:
截图:
ws51t4hk2#
通过回调
self.frame
上的<Configure>
事件,您可以将self.canvas
的宽度设置为与self.frame
相同。另请注意,当self.frame
的大小发生变化时,您需要更新画布的scrollregion
。