我正在尝试制作一个左侧有较小侧边菜单的 tkinter 应用程序,它应该是这样的:
from tkinter import *
root = Tk()
root.geometry("700x500")
root.grid_columnconfigure(0, weight = 1)
root.grid_columnconfigure(1, weight = 2)
root.grid_rowconfigure(0, weight = 1)
left_frame = Frame(root, background = "red")
left_frame.grid_rowconfigure(0, weight = 1)
left_frame.grid_columnconfigure(0, weight = 1)
left_frame.grid(row = 0, column = 0, sticky = "news")
right_frame = Frame(root, background = "blue")
right_frame.grid(row = 0, column = 1, sticky = "news")
root.mainloop()
问题是,如果我尝试将画布放入红色框内,会发生这种情况:
from tkinter import *
root = Tk()
root.geometry("700x500")
root.grid_columnconfigure(0, weight = 1)
root.grid_columnconfigure(1, weight = 2)
root.grid_rowconfigure(0, weight = 1)
left_frame = Frame(root, background = "red")
left_frame.grid_rowconfigure(0, weight = 1)
left_frame.grid_columnconfigure(0, weight = 1)
left_frame.grid(row = 0, column = 0, sticky = "news")
right_frame = Frame(root, background = "blue")
right_frame.grid(row = 0, column = 1, sticky = "news")
c = Canvas(left_frame, borderwidth=0, background = "yellow", highlightthickness=0)
c.grid(row = 0, column = 0, sticky = "news")
root.mainloop()
我原以为黄色画布会在不改变大小的情况下填满红色框架,我哪里错了? 谢谢。
这个效果是由于
sticky
选项的错误使用。
从这个网站中提取
Python tkinter 中的 sticky 有什么用?
当widget小于cell时,sticky用来表示widget贴在cell的哪边和角上。方向由罗盘方向定义:N、E、S、W、NE、NW、SE 和 SW 以及零。
所以
sticky
定义细胞必须粘在哪个点上,在你的情况下定义为 news
这意味着所有四个边。
所以要获得所需的输出,您可以使用
nwsw
.