python-3.x 如何加粗用户在customtkinter的文本框中输入的下一个单词?

dddzy1tm  于 2023-03-13  发布在  Python
关注(0)|答案(1)|浏览(95)

我想自己做一个文字处理软件,但我不知道如何按下按钮,只加粗用户接下来要输入的内容,而不是整个文本框。

# from tkinter import *  # PEP8: `import *` is not preferred`
import customtkinter as tk
#from docx import Document


class TextWindow(tk.CTkToplevel):  # still use `Toplevel`

    def __init__(self, master):  # send main window as master/parent
        super().__init__(master)  # it will also set `self.master = master`

        ws = self.winfo_screenwidth()  # width of the screen
        hs = self.winfo_screenheight()  # height of the screen

        # calculate x and y coordinates for the Tk root window
        x = (ws / 2) - (300 / 2)
        y = (hs / 2) - (200 / 2)

        self.geometry('%dx%d+%d+%d' % (300, 200, x, y))
        self.title("New World Documents")
        tk.set_appearance_mode("system")
        tk.set_default_color_theme("green")

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure((0, 1), weight=1)

        self.textbox = tk.CTkTextbox(self, width=400, corner_radius=0, font=("roboto", 12), wrap="word")
        self.textbox.grid(row=0, column=0, padx=20, pady=20, sticky="nsew", columnspan=2)

        self.button = tk.CTkButton(self, text="Save and quit", command=self.go_back)
        self.button.grid(row=1, column=0, padx=20, pady=20, sticky="ew")

        self.button1 = tk.CTkButton(self, text="Bold", command=self.bolden)
        self.button1.grid(row=1, column=1, padx=20, pady=20, sticky="ew")

        self.wm_protocol("WM_DELETE_WINDOW", self.on_close)

    def bolden(self):
        #Function to bolden what the user will type.
        self.textbox.configure(font=("roboto", 12, "bold"))

    def go_back(self):
        # Work in Progress.
        #document = Document()
        #text = self.textbox.get("1.0", "end-1c")
        #document.add_paragraph(text)
        #document.save("test.docx")
        #with open("filepy.txt", "a") as outf:
        #    outf.write(text)
        self.destroy()  # destroy only current window
        self.master.deiconify()  # show again main window

    def on_close(self):
        self.destroy()  # destroy current window
        self.master.destroy()  # destroy main window

class MainScreen(tk.CTk):

    def __init__(self):
        super().__init__()

        ws = self.winfo_screenwidth()  # width of the screen
        hs = self.winfo_screenheight()  # height of the screen

        # calculate x and y coordinates for the Tk root window
        x = (ws / 2) - (300 / 2)
        y = (hs / 2) - (200 / 2)

        self.geometry('%dx%d+%d+%d' % (300, 200, x, y))
        self.title("New World Documents")
        tk.set_appearance_mode("system")
        tk.set_default_color_theme("green")

        self.label = tk.CTkLabel(self, text="New World Documents", font=("roboto",25), width=200, height=25)
        self.label.pack()

        self.button = tk.CTkButton(self, text="New Document", command=self.StartWriting)
        self.button.pack()

    def StartWriting(self):
        self.withdraw()
        self.app = TextWindow(self)  # send main window as argument

    def start(self):
        self.mainloop()

MainScreen().start()

目前,当我按下粗体按钮时,代码所做的唯一事情就是将文本框中的所有内容都加粗,我只想将下一个要输入的单词加粗,就像word、libreoffice、google docs等。
我试过查找答案,但每次我接近标签时,答案都无济于事,因为它只适用于从代码中插入的单词,而不适用于从键入的单词,它也不起作用,因为我无法指定为空格或未来将要键入的单词添加标签。

bnlyeluc

bnlyeluc1#

当你按下键盘上的一个键时,它会被小部件类上的<Key>事件的绑定处理。你可以在小部件上创建一个到同一事件的绑定,并覆盖默认行为。如果绑定函数返回字符串"break",它将阻止小部件类上的绑定被处理。
在下面的示例中,创建了一个类,该类使用一个将标记列表附加到每个插入字符的自定义函数重写默认绑定。

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.tags = []
        self.bind("<Key>", self._key)

    def _key(self, event):
        if event.char:
            # ie: if it's a printable character
            # insert the character along with the set of tags
            self.insert("insert", event.char, self.tags)

            # ... and prevent the default binding from processing
            # the event
            return "break"

您可以创建菜单项或工具栏按钮,将tags属性设置为所需的任何值。例如,您可以为“bold”配置一个标记,并将工具栏按钮配置为在选定按钮时添加“bold”标记。
下面的示例定义标记“bold”,以及一个用于在标记列表中添加或删除“bold”的复选按钮。

import tkinter as tk
from tkinter.font import Font

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.tags = []
        self.bind("<Key>", self._key)

    def _key(self, event):
        if event.char:
            # ie: if it's a printable character
            # insert the character along with the set of tags
            self.insert("insert", event.char, self.tags)

            # ... and prevent the default binding from processing
            # the event
            return "break"

def set_attributes():
    tags = []
    for tag, var in vars.items():
        if var.get():
            tags.append(tag)
    text.tags = tags

root = tk.Tk()

text_font = Font(family="helvetica", size=20)
bold_font = Font(family="helvetica", size=20, weight="bold")

text = CustomText(root, font=text_font)
toolbar = tk.Frame(root)

toolbar.pack(side="top", fill="x")
text.pack(fill="both", expand=True)

vars = {"bold": tk.BooleanVar()}

bold_button = tk.Checkbutton(
    toolbar, text="Bold", command=set_attributes,
    onvalue=True, offvalue=False, indicatoron=False,
    variable=vars["bold"]
)
bold_button.pack(side="left")

text.tag_configure("bold", font=bold_font)

root.mainloop()

相关问题