簡體   English   中英

如何設置字體大小以適應 tkinter 中框架的特定寬度

[英]How to set Font size to fit a specific width of the frame in tkinter

實際上,我正在 python 中的 tkinter 的幫助下制作一個項目,所以基本上我想根據將要放入的框架的寬度縮小label的字體大小。我只想給出一個字符串,它會根據寬度自動調整字體大小 例如:- 讓我給出一個字符串“Hotel Raj Kundra and Family Resturant”,讓框架/標簽的寬度為 500。那么它將如何自動調整為 window 這個大小而不包裹文本。 正好適合 window 尺寸

with.config 你可以在放置后調整屬性。 現在您可以使用字符串的 len() 調整 window 的大小。 我希望它有所幫助。

import tkinter as tk

def adjust_Window(canvas, text):

    canvas.config(width=len(text)*50)

def main():
    root = tk.Tk()

    canvas = tk.Canvas(root, width=500, height=500)
    canvas.pack()

    adjust_Window(canvas, "i hope it helps <3")

    root.mainloop()


if __name__ == '__main__':
    main()

更簡單的方法:

from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

def update_width():
   l.configure(text='Hotel Raj Kundra and Family Resturant', background='blue', foreground='white', font=("Calibri,8,itlaic"))
   

# Create a frame
frame=Frame(win, background="skyblue3", width=700, height=250)
frame.pack()

# Add a button in the main window
ttk.Button(win, text="Update", command=update_width).pack()
l = ttk.Label(win, background='red', text="so how it will automatically adjust in this size of window without wrapped the text. just fit in the window siz" , font=("Calibri,32,Bold"))
l.pack()
          
win.mainloop()

結果最寬:

在此處輸入圖像描述

縮小的結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM