【问题标题】:Python - Tkinter button size changes when chaging the size of its fontPython - Tkinter 按钮大小在更改其字体大小时发生变化
【发布时间】:2020-11-02 01:10:28
【问题描述】:

我想更改 Tkinter 按钮中的字体大小。但是按钮大小会随之变化。 我什至试图限制按钮的高度和宽度,但似乎没有任何效果, 这是代码:

from tkinter import *

root = Tk()
root.geometry("500x300")
root.resizable(False, False)
button = Button(root, text="Ihsan", bg="Black", fg="white",
                activeforeground="white", activebackground="grey", width=15, height=3,
                font=("ariel", "43"))
button.place(x=350, y=20)
root.mainloop()

我得到一个带有大按钮的窗口。请帮忙

【问题讨论】:

  • 您希望它是什么尺寸?您是否尝试创建一个太小而无法显示文本的按钮?
  • @BryanOakley 我想在不增加按钮大小的情况下放大按钮中的文本。
  • 由于您使用了place(),您可以在其中指定像素大小:button.place(x=350, y=20, width=200, height=50)

标签: python tkinter


【解决方案1】:

按钮的宽度和高度,以字母(如果显示文本)或像素(如果显示图像)为单位。

这是一种方法,通过在字体大小更改时使用图像大小来限制按钮的大小。不知道是不是最好的。

import tkinter as tk
from PIL import Image, ImageTk

def new_font():
    global setting
    setting = 1 - setting
    font = f"ariel {32 if setting else 16}"
    button.configure(font=font)

setting = 0

root = tk.Tk()

im = Image.new("RGB", (200, 200))
photo = ImageTk.PhotoImage(im)

root.geometry("300x300")
root.resizable(False, False)
button = tk.Button(
    root,
    text="Ihsan",
    bg="Black",
    fg="white",
    activeforeground="white",
    activebackground="grey",
    width=200,
    height=200,
    font=("ariel", "16"),
    image=photo,
    compound='center')

button.place(x=30, y=20)
size = tk.Button(root, text="Size", command=new_font)
size.place(x=30, y=250)

root.mainloop()

【讨论】:

  • 有没有办法在没有图片的情况下做到这一点
  • @ihsan:您可以创建一个不可见的 1x1 像素图像以及文本。像素的使用将导致小部件以像素而不是字符来调整大小。
【解决方案2】:

宽度和高度是为您提供大按钮的原因。在这种情况下,高度意味着 3 fontsize 高。 默认是只包含文本。

您使用 pad 提供的边距,无论是在小部件本身中,还是在您打包时。 使用 place 有点不常见,并且有其特定的用例,看起来你不需要它。可以使用 pack 几何管理器。

from tkinter import *

root = Tk()
root.geometry("500x300")
root.resizable(False, False)
button = Button(root, text="Ihsan", bg="Black", fg="white",
                activeforeground="white", activebackground="grey",# width=15, height=3,
                font=("ariel", "43"))
#button.place(x=350, y=20)
button.pack(side=RIGHT)
root.mainloop()

【讨论】:

    猜你喜欢
    • 2017-08-07
    • 2018-01-02
    • 2018-09-27
    • 2013-06-20
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多