【问题标题】:How to change the size of the text inside the Buttons?如何更改按钮内文本的大小?
【发布时间】:2020-05-13 09:00:58
【问题描述】:

有人可以帮我解决这个问题吗?我花了 1 天时间在网上搜索一个体面的答案,但一无所获!

'''
Created on 20 gen 2020

@author: ruben
'''
from tkinter import *
import os
import random
from _sqlite3 import Row
import math
from lib2to3.pgen2.token import OP


op = "suca"
num1 = 234
num2 = 0
#CalculatorGui
gui = Tk()
gui.geometry("320x427") 
gui.title("Calculator")


#ScientificCalculator
#def RAD():


#TextArea
text = Text(gui, height='5', width='30')
text.grid(row=0, column=0, columnspan=5, ipadx=37)    
#Buttons
n1 = Button(gui, text='1', fg='black', bg='grey', height='5', width='10', command=press1)
n1.grid(row=1, column=0) 

gui.mainloop()

这只是所有代码的 5%。我只需要更改按钮n1 = Button(gui, text='1', size?内的文本大小

【问题讨论】:

标签: python tkinter


【解决方案1】:

在按钮调用中使用字体参数。

Button(gui, text='1', fg='black', bg='grey', height='5', width='10', command=press1, font=("Helvetica", 20, "bold"))

【讨论】:

    【解决方案2】:

    可以在创建小部件时或使用小部件的配置方法时使用字体配置选项来更改小部件的字体大小。可以使用包含字体名称的元组或字符串来提供字体,还可以选择大小和样式。

    n1 = Button(gui, text='1', font=('FontName', 16, 'style'))
    n1 = Button(gui, text='1', font='FontName 16 style')
    n1.config(font=('FontName', 16, 'style'))
    n1.config(font='FontName 16 style')
    

    以上是完成相同任务的四个选项。要像这样更改文本的大小,您需要在提供文本大小之前提供字体名称。这意味着,如果您希望按钮的文本与其他按钮中的文本相匹配,您需要知道正在使用什么字体。如果您已经为其余小部件手动设置了字体,请使用该字体。但是如果你没有设置字体,你可以使用按钮的cget()方法来确定默认字体的名称。

    n1 = Button(gui, text='1')
    font = n1.cget('font')
    n1.config(font=(font, 16))
    

    更多关于样式小部件的信息在这里:https://effbot.org/tkinterbook/tkinter-widget-styling.htm

    【讨论】:

    • n1.config(font=(font, 16)) 行并没有像您认为的那样做。例如,如果字体先前设置为"Courier 24",那么n1.config(font=(font, 16)) 将与n1.config(font=("Courier 24" 16)) 相同,并且由于“Courier 24”不是有效字体的名称,tkinter 将替换默认字体。
    • @BryanOakley 不要字体默认为 TkDefaultFont 之类的东西?对于 Courier 24 字体,Ruben 必须手动选择该字体,这意味着他不需要使用 cget('font') 来查找匹配字体的名称。我建议他使用cget('font') 来查找默认名称,因为它可能因小部件或平台而异。如果我错了,请纠正我。
    • 是的,字体可能(虽然不是绝对)默认为TkDefaultFont,但不能保证它没有被更改。这不是一个好的通用解决方案,因为它只能工作一次,并且只能在某些条件下工作。将字体设置为某个值后,它将不再起作用。
    猜你喜欢
    • 2017-06-08
    • 2017-03-09
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多