You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter中grid_propagate失效求助:粉色标签仍自动调整大小

Fixing grid_propagate Not Working for Your Pink Course Labels in Tkinter

Let's break down why your pink course labels keep resizing even after trying grid_propagate(False), and fix it step by step:

The Core Problem

You’re calling label.grid_propagate(False) on your course labels, but grid_propagate() only affects container widgets (like Frame or LabelFrame—widgets that hold other elements). Regular Label widgets aren’t containers, so this line does nothing at all.

Even if you disable propagation on the parent coursePlan frame, the grid columns and rows holding your course labels don’t have fixed sizes. When you switch fonts, the label’s text takes up more space, which stretches the grid cell—and the label stretches right along with it.

Step-by-Step Solution

  1. Lock the parent frame’s size
    Call self.grid_propagate(False) in your coursePlan class’s __init__ method. This prevents the frame from resizing when its child widgets change size.

  2. Fix grid column/row dimensions
    After creating your initial time and weekday labels, set fixed pixel sizes for the weekday columns (1-5) and time rows (1-24). This locks the grid cells so they won’t stretch when labels update.

  3. Adjust course label setup
    Remove the width and height parameters from your course label (we’ll rely on the fixed grid cell size instead), and keep sticky=NSEW to ensure the label fills the cell completely.

Modified Code Snippets

First, update your __init__ method:

def __init__(self,master):
    Frame.__init__(self,master)
    self.bgcolor='mint cream'
    self['bg']=self.bgcolor
    self.buttonColor='SeaGreen1'
    self.labelWidth=18
    self.buttonWidth=6
    
    # Disable propagation to lock the frame's size
    self.grid_propagate(False)
    
    # Your existing Time/Weekday label code
    Label(self,text='Time',relief=FLAT,bg='#00ffff',\
          width=self.buttonWidth,height=1).grid(row=0,column=0,sticky=NSEW)
    self.aweekday=['m','t','w','r','f']
    self.weekday=['Mon','Tue','Wed','Thu','Fri']
    self.time=['{}:{}0'.format((i//2+7)%12+1,[0,3][i%2]) for i in range(24)]
    for i,date in enumerate(self.weekday):
        Label(self,text=date,relief=FLAT,bg='#00{}ff'.format(hex(250-i*25)[2:]),\
              width=self.labelWidth,height=1).grid(row=0,column=i+1,sticky=NSEW)
    for i,time in enumerate(self.time):
        Label(self,text=time,relief=FLAT,bg='#00{}ff'.format(hex(250-i*5)[2:]),\
              width=self.buttonWidth,height=1).grid(row=i+1,column=0,sticky=NSEW)
    
    # FIX: Set fixed pixel sizes for weekday columns (1-5)
    for col in range(1, 6):
        self.grid_columnconfigure(col, width=120)  # Adjust to your desired width
    
    # FIX: Set fixed pixel sizes for time rows (1-24)
    for row in range(1, 25):
        self.grid_rowconfigure(row, height=30)  # Adjust to your desired height
    
    # Rest of your __init__ code (entry boxes, buttons, etc.)
    self.timeLabel=Label(self,text='Time:')
    self.timeBox=Entry(self)
    self.exampleText='Example: tr12-1:15'
    self.timeBox.bind('<FocusIn>',self.focusIn)
    self.timeBox.bind('<FocusOut>',self.focusOut)
    self.nameLabel=Label(self,text='Name:')
    self.nameBox=Entry(self)
    self.locLabel=Label(self,text='Location:')
    self.locBox=Entry(self)
    self.boxList=[self.timeBox,self.nameBox,self.locBox]
    for i,(box,label) in enumerate(zip(self.boxList,[self.timeLabel,self.nameLabel,self.locLabel])):
        label.configure(anchor='n',\
                       bg='lavender',\
                       bd=0,\
                       height=1,\
                       width=self.labelWidth//2,\
                       relief=FLAT)
        label.grid(row=i,column=6,sticky=NSEW)
        box.configure(bg='lavender',\
                     bd=0,\
                     width=3*self.labelWidth//2,\
                     relief=FLAT)
        box.grid(row=i,column=7,columnspan=2,sticky=NSEW)
        box.bind('<KeyRelease>',self.switch)
    self.setup()
    self.addButton=Button(self,text='Add',command=self.add)
    self.clearButton=Button(self,text='Clear',command=self.clear)
    self.readButton=Button(self,text='Read',command=self.read)
    self.saveButton=Button(self,text='Save',command=self.save)
    self.colorButton=Button(self,text='Color',command=self.switchColor)
    self.fontButton=Button(self,text='Font',command=self.switchFont)
    buttonList=[self.addButton,self.clearButton,self.readButton,self.saveButton,self.colorButton,self.fontButton]
    for i,button in enumerate(buttonList):
        self.configureButton(button)
        button.grid(row=i//2,column=9+i%2,sticky=NSEW)
    Label(self,text='Course List',relief=FLAT,bg='DeepSkyBlue',\
          bd=0,width=2*self.labelWidth,height=1).grid(row=3,column=6,columnspan=3,sticky=NSEW)
    self.read()

Then, update your putLabel method to remove the useless grid_propagate call and unnecessary size parameters:

def putLabel(self,datetime,name,loc,mode=0):
    ## part of the code for the pink label
    for weekday in datetime[:weekindex]:  # Assuming weekindex is defined elsewhere
        day=self.weekday[self.aweekday.index(weekday)]
        label=Label(self,text=name+'\n'+loc,bg=self.colorList[0],font=self.fontList[0],\
                    bd=0, relief=FLAT)  # Removed width/height
        self.courseLabels[index].append(label)  # Assuming index is defined elsewhere
        label.grid(row=self.time.index(start)+1,column=self.weekday.index(day)+1,rowspan=grids,sticky=NSEW)
        # Removed label.grid_propagate(False) — it has no effect here

Extra Tips

  • To lock the root window size too, add root.resizable(False, False) after packing the coursePlan frame.
  • Adjust the width and height values in grid_columnconfigure/grid_rowconfigure to match your ideal label dimensions.
  • If you want text to wrap instead of getting cut off, add wraplength=110 (adjust to match your column width) to the course label creation.

内容的提问来源于stack exchange,提问作者Seaky Lone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:49:44