以下代码创建一个内部有框架的画布。我正在使用画布启用添加垂直滚动条,必要时会显示该滚动条。我把各个部分着色了 - 根,蓝色;窗户,绿色;帆布,红色和框架,青色。由此可以看出窗口完全填满根(没有看到蓝色)。但是,画布仅在垂直方向上填充窗口(在展开窗口时绿色可见绿色,框架仅在水平方向填充画布(红色在青色下方可见)。我无法看到导致问题的原因。框架是绑定到画布和画布有sticky ='nsew'设置所以应该填充窗口。
import Tkinter as tk
import tkFileDialog
class AutoScrollbar(tk.Scrollbar):
# a scrollbar that hides itself if it's not needed. only
# works if you use the grid geometry manager.
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
# grid_remove is currently missing from Tkinter!
self.tk.call("grid", "remove", self)
else:
self.grid()
tk.Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError, "cannot use pack with this widget"
def place(self, **kw):
raise TclError, "cannot use place with this widget"
class Window(tk.Frame):
def UserInput(self,status,name):
row = self.row
optionLabel = tk.Label(self.frame)
optionLabel["text"] = name
optionLabel.grid(row=row, column=0, sticky='w')
var = tk.StringVar(root)
var.set(status)
w = tk.Entry(self.frame, textvariable= var)
w.grid(row=row, column=1, sticky='ew')
self.grid_columnconfigure(1,weight=1)
self.row += 1
return w
def on_canvas_resize(self,event):
padding = 8
width = self.canvas.winfo_width() - padding
self.canvas.itemconfigure("frame", width=width)
def OnFrameConfigure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def __init__(self,parent):
tk.Frame.__init__(self,parent)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0,weight=1)
self.vscrollbar = AutoScrollbar(self,orient = tk.VERTICAL)
self.vscrollbar.grid(row = 0,column = 3, sticky = 'ns')
self.canvas = tk.Canvas(self, yscrollcommand = self.vscrollbar.set,bg='red')
self.canvas.grid(row=0, column=0, sticky='nsew')
self.canvas.grid_rowconfigure(0, weight = 1)
self.canvas.grid_columnconfigure(0, weight = 1)
self.frame = tk.Frame(self.canvas, bg='cyan')
self.frame.bind("<Configure>", self.OnFrameConfigure)
self.frame.grid_rowconfigure(0, weight=1)
self.frame.grid_columnconfigure(0,weight=1)
self.frame.grid_columnconfigure(1,weight=3)
self.vscrollbar.config(command=self.canvas.yview)
self.canvas.create_window(0, 0, anchor = tk.NW, window= self.frame, tags =["frame"])
self.canvas.bind("<Configure>", self.on_canvas_resize)
self.row = 0
for i in range(10):
self.Number = self.UserInput("1", "number")
if __name__ == "__main__":
root = tk.Tk()
root.configure(background='blue')
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0,weight=1)
window = Window(root)
window.configure(background='green')
window.grid(row=0,column=0,sticky='nsew')
root.mainloop()
答案 0 :(得分:1)
您将画布放在第0列(零)中,并且您正确地为该列赋予了权重。但是,您还要给第1列(一行)赋予相同的权重(参见第29行),这会阻止画布填充窗口。删除第29行,即将第1列的权重设置为1.
您的框架水平填充画布,因为这是您要告诉它的。如果你想要它也是同一个高度,你也需要设置它的高度。