簡體   English   中英

在 Tkinter 中以粗體和較小的尺寸打印文本

[英]Print the text in bold and smaller size in Tkinter

我想打印變量x ,所以文本“Example1”以粗體顯示。 此外,我想打印較小尺寸的文本變量y :只有尺寸較小的變量 y。

web 上有示例,但與我的情況不同,因為我使用 f" 和 {xxx}。

這是一個可執行代碼示例,如果您想幫助我,可以使用它。 謝謝

from tkinter import ttk
import tkinter as tk
from tkinter import *

root = tk.Tk()
root.geometry("400x150")

textbox = tk.Text(root,width=48,height=4)
textbox.place(x=1, y=5)
  
x = "Example1"
y = "Example2"
              
def print():
        
    text = f"A sentence that contains the variable: {x}" \
           f"\n \n This must possess smaller size: {y} " 
           
    textbox.insert(tk.END, text)

button2 = Button(root, text="Print", command = print)
button2.pack()
button2.place(x=15, y=100)

我相信沒有直接的方法來格式化變量,因為在 Text 小部件中它只是一個字符串。 您可以使用帶有tag_addtag_configure方法的索引來格式化特定文本。 例如在這種情況下,第一行的最后一個單詞是粗體,而第三行的最后一個單詞(注意,第二行是空的,由於額外的\n )應該更小。

在下面的代碼1.end-1c wordstart意味着轉到第 1 行的末尾(即\n )減去 1 個字符(即x的最后一個字母),然后轉到該單詞的起始字符。 1.end-1c wordend表示轉到x的最后一個字符。 對於y也是如此。

from tkinter import ttk
import tkinter as tk
from tkinter import *

root = tk.Tk()
root.geometry("400x150")

textbox = tk.Text(root,width=48,height=4)
textbox.place(x=1, y=5)
  
x = "Example1"
y = "Example2"
              
def print():
        
    text = f"A sentence that contains the variable: {x}" \
           f"\n \n This must possess smaller size: {y} " 
           
    textbox.insert(tk.END, text)

    textbox.tag_add("setbold", "1.end-1c wordstart", "1.end-1c wordend")
    textbox.tag_configure("setbold", font="Arial 13 bold")
    textbox.tag_add("setsmall", "3.end-1c wordstart", "3.end-1c wordend")
    textbox.tag_configure("setsmall", font="Arial 5")

button2 = Button(root, text="Print", command = print)
button2.pack()
button2.place(x=15, y=100)

試試看這里: https ://tkdocs.com/tutorial/text.html。 我不知道這是否可以幫助你。 但是,您必須創建一個函數來指定 x 和 y。

暫無
暫無

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

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