如何调整“标签”和“文本”小部件填充调整“root”的所有空间?
如果可能,我想使用'grid'方法。
from tkinter import *
root = Tk()
root.resizable(width = True, height = True)
label = Label(root, text = "Text")
label.grid()
text = Text(root)
text.grid()
root.mainloop()
当我尝试在课堂上使用时,它不起作用。
Application.py
from tkinter import *
import menu
import workPlace
class Application(Frame):
def __init__(self, boss = None):
Frame.__init__(self)
self.master.title("Title")
self.master.grid_columnconfigure(0, weight = 1)
self.master.grid_rowconfigure(1, weight = 1)
self.master.resizable(width = True, height = True)
self.menu = menu.MenuBar(self)
self.menu.grid(sticky = W)
self.workPlace = workPlace.WorkPlace(self)
self.workPlace.grid(sticky = "NEWS")
if __name__ == "__main__":
Application().mainloop()
workPlace.py
from tkinter import *
import tkinter.scrolledtext as scr
class WorkPlace(Frame):
def __init__(self, boss = None):
Frame.__init__(self)
self.scrText = scr.ScrolledText(self)
self.scrText.grid()
self.label = Label(self,text = "Label")
self.label.grid()
menu.py
from tkinter import *
class MenuBar(Frame):
def __init__(self, boss = None):
Frame.__init__(self)
fileMenu = Menubutton(self, text = 'File')
fileMenu.grid(row = 0, column = 0)
me1 = Menu(fileMenu)
fileMenu.configure(menu = me1)
findMenu = Menubutton(self, text = 'Find')
findMenu.grid(row = 0, column = 1)
me1 = Menu(findMenu)
findMenu.configure(menu = me1)
optionMenu = Menubutton(self, text = 'Option')
optionMenu.grid(row = 0, column = 2)
me1 = Menu(optionMenu)
optionMenu.configure(menu = me1)
答案 0 :(得分:4)
需要两个步骤。
调用grid_rowconfigure
和grid_columnconfigure
设置每个网格行和列的权重。在调整大小期间,权重为零的行和列根本不会伸展。这是默认行为。
在小部件上调用grid
时,请指定sticky
参数,以便小部件在行或列延伸时拉伸。
from tkinter import *
root = Tk()
root.grid_columnconfigure(0, weight=1)
#uncomment this line if you want the Label widget to stretch vertically.
#or leave it as is if you only want the Text widget to stretch.
#root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.resizable(width = True, height = True)
label = Label(root, text = "Text")
label.grid(sticky="NEWS")
text = Text(root)
text.grid(sticky="NEWS")
root.mainloop()
在WorkPlace对象的特定情况下,您需要configure
根对象和WorkPlace对象,并且需要为WorkPlace对象及其子对象指定粘性。
from tkinter import *
import tkinter.scrolledtext as scr
class WorkPlace(Frame):
def __init__(self, boss = None):
Frame.__init__(self)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.scrText = scr.ScrolledText(self)
self.scrText.grid(sticky="NEWS")
self.label = Label(self,text = "Label")
self.label.grid()
答案 1 :(得分:2)
如果您可以使用pack
代替grid
,则可以
from tkinter import *
root = Tk()
root.resizable(width = True, height = True)
label = Label(root, text = "Text")
label.pack(fill=X)
text = Text(root)
text.pack(fill=BOTH, expand=True)
root.mainloop()