简体   繁体   中英

Dynamic Size Change in Tkinter messing up

I'm trying to configure my text to be a certain size if its window size is too large. This is the code I'm using.

def res(e):
    h=e.height

    if h>180.0:
        l.config(font=("Cambria",30,"bold"))
    elif h<=180.0:
        l.config(font=("Cambria",20,"bold"))

#configuration
gui.geometry("500x300")
gui.minsize(500, 300)

Grid.rowconfigure(gui, 0, weight=1)
Grid.columnconfigure(gui, 0, weight=1)
Grid.rowconfigure(gui, 1, weight=1)
Grid.columnconfigure(gui, 1, weight=1)
Grid.rowconfigure(gui, 2, weight=1)
Grid.columnconfigure(gui, 2, weight=1)

l=Label(gui, text="Welcome!", pady=20, padx=20)
l.grid(row=0,column=0, sticky="nsew", columnspan=3)

gui.bind('<Configure>', res)

#calling GUI
gui.mainloop()

(There is a bit more code in the actual program but it's too bulky to post here. This is the portion with the problem.)

There's a particular size of the window in which the text starts alternating between the two sizes rapidly. This also happens every time I move the tkinter window or any time I open it after it has been minimized.

Any idea how I could fix this? I've tried setting the values of height as int instead of float and tried using the else statement instead of elif for the conditions but nothing seems to work.

When you initialize the font, set the variable as

self.font = SOME_BASE_FONT
self.labelName.config(font = self.font)

Then you can use:

self.font = tkFont.Font(size = PIXEL_HEIGHT)

And finally you can define your callback function to resize as follows:

def resize(self, event):
    self.font = tkFont(size = widget_height)

As event binding on root window will inherit to its children, so the function will be executed when its children is resized as well. You can do the font resize only when the function is triggered by resize of root window:

def res(e):
    if e.widget is gui:
        fs = 30 if e.height > 180 else 20
        l.config(font=("Cambria",fs,"bold"))

I found a solution to this. In the res function instead of setting h to e.height , use:

gui.update()
h=gui.winfo_height()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM