[英]how increase font size in text widget?
當我使用以下代碼增加字體的大小時,它也會增加小部件的大小。 是否可以通過保持文本小部件的大小不變來增加字體大小? 謝謝
A11 = tkinter.Text(top, height=28, width=70,background = "#02e0a1")
labelfont = ('times', 20, 'bold')
A11.config(font = labelfont)
如果強制GUI窗口為特定大小,則更改文本小部件的字體不會導致文本小部件增長*。 通常有助於將文本小部件的寬度和高度設置為1(一),以便在更改字體時甚至不會嘗試增長。
這是一個簡單的人為例子。
import tkinter as tk
import tkinter.font as tkFont
class Example(object):
def __init__(self):
root = tk.Tk()
self.font = tkFont.Font(family="helvetica", size=18)
text = tk.Text(root, width=1, height=1, font=self.font)
button = tk.Button(root, text="Bigger", command=self.bigger)
button.pack(side="top")
text.pack(side="top", fill="both", expand=True)
text.insert("end", "Hello, world!")
# force the widow to a specific size after it's created
# so that it won't change size when we change the font
root.geometry("800x400")
def start(self):
tk.mainloop()
def bigger(self):
size = int(self.font.cget("size"))
size += 2
self.font.configure(size=size)
app = Example()
app.start()
通過將大小約束放在框架而不是根窗口上,相同的技術可以在較小的規模上工作。 如果將文本窗口小部件放在框架內,關閉幾何體傳播,然后為框架提供固定大小,窗口小部件將不會增長。 這是關閉幾何傳播的少數幾次之一。
以下是使用此技術對上述示例的修改:
import tkinter as tk
import tkinter.font as tkFont
class Example(object):
def __init__(self):
root = tk.Tk()
self.font = tkFont.Font(family="helvetica", size=18)
button = tk.Button(root, text="Bigger", command=self.bigger)
# create a frame for the text widget, and let it control the
# size by turning geometry propagation off
text_frame = tk.Frame(root, width=800, height=400)
text_frame.pack_propagate(False)
text = tk.Text(text_frame, width=1, height=1, font=self.font)
text.pack(side="top", fill="both", expand=True)
button.pack(side="top")
text_frame.pack(side="top", fill="both", expand=True)
text.insert("end", "Hello, world!")
def start(self):
tk.mainloop()
def bigger(self):
size = int(self.font.cget("size"))
size += 2
self.font.configure(size=size)
app = Example()
app.start()
小部件大小由字體大小決定,因此對於大字體,小字體的寬度= 10小於寬度= 10。 以下代碼僅更改字體大小。
import sys
if sys.version_info[0] < 3:
import Tkinter as tk ## Python 2.x
else:
import tkinter as tk ## Python 3.x
class DifferentFonts():
def __init__(self):
self.top=tk.Tk()
tk.Label(self.top, text="Small Font", width=10, bg="lightblue",
font=('DejaVuSansMono', 10)).grid(row=1)
tk.Label(self.top, text="Large Font", width=10, bg="lightyellow",
font=('DejaVuSansMono', 30)).grid(row=2)
tk.Button(self.top, text="Quit", bg="orange",
command=self.top.quit).grid(row=20)
self.top.mainloop()
DifferentFonts()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.