python - 如何在 tkinter 中加粗选定的文本?
问题描述
我在 python 中制作了一个文本编辑器,但我遇到了一些问题。它有一个bold加粗文本编辑器的整个文本的按钮,我想在其中将其应用于选定的文本,但我无法正确定义功能。
请帮我选择文本和粗体。
这是我的代码:
#bold
bold_icon = tk.PhotoImage(file='C:\\Users\\soham\\OneDrive\\Desktop\\TEXT_EDITOR\\ICONS\\icons2\\bold.png')
bold_btn = ttk.Button(tool_bar, image= bold_icon)
bold_btn.grid(row=0, column=2, padx=5)
def change_bold():
text_property=tk.font.Font(font=text_editor['font'])
if text_property.actual()['weight'] =='normal':
text_editor.configure(font=(current_font_family, current_font_size, 'bold'))
if text_property.actual()['weight'] == 'bold':
text_editor.configure(font=(current_font_family, current_font_size, 'normal'))
bold_btn.configure(command=change_bold)
解决方案
将您的功能更改为:
def change_bold():
textwidget.tag_configure("boldtext",font=textwidget.cget("font")+" bold")
textwidget.tag_add("boldtext","sel.first","sel.last")
要使文本再次正常,您应该将函数更改为:
textwidget.tag_configure("boldtext",font=textwidget.cget("font")+" bold")
def change_bold():
if "boldtext" in textwidget.tag_names("sel.first"):
textwidget.tag_remove("boldtext","sel.first","sel.last")
else:
textwidget.tag_add("boldtext","sel.first","sel.last")
推荐阅读
- c++ - 如何声明具有 C 链接的函数指针?
- sql - 通过使用 Oracle 连接两个表来更新列
- java - 在 xml drawable 中使用 ?colorVariant 时,Android Studio 应用程序在启动时崩溃
- authentication - 使用 Okta 身份验证发出 Google Drive API 请求
- r - 如何在 R 中的非结构化系列中删除常规月份的观察?
- vue.js - Vuejs 中 Axios API 中最不喜欢的
- java - 嵌套 for 循环到 lambda - Java
- c - 文件传输后无法使用套接字 - C Socket
- azure - Azure Functions 代理似乎正在缓存响应
- c++ - 递增常量指针变量在 for 循环中工作