[英]Canvas not filling available space tkinter
我正在嘗試使用 tkinter 作為 gui 界面制作消息傳遞程序。 在 gui 的左側,有一個畫布,里面有數字 1 - 100。 畫布一側還有一個滾動條可以滾動這些數字。
問題是畫布不會填滿所有可用空間,並且由於某種原因將自己限制在一個小盒子里。
代碼:
from tkinter import *
# *** Scrollable Frame Class ***
class VerticalScrolledFrame(Frame):
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=LEFT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set, bg="black")
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
canvas.xview_moveto(0)
canvas.yview_moveto(0)
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
def _on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
self.interior.bind_all("<MouseWheel>", _on_mousewheel)
canvas.bind_all("<MouseWheel>", _on_mousewheel)
def _configure_interior(event):
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
# *** Create Window ***
root = Tk()
root.geometry("800x545")
root.config(bg="#23272A")
#root.resizable(False, False)
root.title("Secure Message")
# *** Set Friends Frame ***
friends_frame = VerticalScrolledFrame(root)
friends_frame.pack(side=LEFT)
for i in range(100):
friend_frames = []
friend_frame = Frame(friends_frame.interior, width=100)
friend_frames.append(friend_frame)
friend_frames[-1].pack()
text = Label(friend_frame, text=i)
text.pack(side=LEFT)
chatSpace_frame = Frame(root)
chatSpace_frame.pack(side=RIGHT)
# *** GUI ***
chatSpace = Listbox(chatSpace_frame, bg="#2C2F33", fg="white", width = 65, height=29)
chatSpace.grid(row=0, column=1, sticky=E, padx=10)
user_input = Entry(chatSpace_frame, highlightbackground="#2C2F33", bg="grey", width = 64, fg="white")
user_input.grid(row=1, column=1, sticky=E, pady=10, padx=9)
user_input.focus()
root.mainloop()
如果有點難以理解,我很抱歉。 任何幫助將不勝感激!
截圖
左側帶有數字的畫布需要填充聊天空間旁邊的所有空白灰色空間。
即使您還沒有發布運行的代碼,但問題似乎很明顯不在於畫布,而在於它所在的框架。
這是問題所在:
friends_frame.pack(side=LEFT)
您沒有讓friends_frame
展開,因此其中的畫布無法展開。 您需要在框架上設置expand
和/或fill
選項。
問題是friends_frame
沒有設置為同時填充X 和Y,並且expand 需要設置為true。
例子
# *** Set frame for friends view ***
friends_frame = VerticalScrolledFrame(root, bg="#23272A")
friends_frame.pack(side=LEFT, fill=BOTH, expand=TRUE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.