Tkinter如何删除组合框小部件中的粗体文本和焦点?

2024-09-29 23:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

为了使ComboBox小部件散焦,我使用示例中编写的“散焦”自定义函数:

from tkinter import *
from tkinter import ttk

def Defocus(event):
    event.widget.master.focus_set()

parent=Tk()
parent.geometry("530x280+370+100")
parent.title("TEST")
parent.configure(background="#f0f0f0")
parent.minsize(485, 280)

SV=StringVar()
SV.set("I hate to see the bold text..")
MenuComboBox=ttk.Combobox(parent, state="readonly", values=("I hate to see the bold text..", "ciao", "hola", "hello"), textvariable=SV, width=50)
MenuComboBox.bind("<FocusIn>", Defocus)
MenuComboBox.place(x=20, y=20)

SV2=StringVar()
SV2.set("I hate to see the bold text..")
MenuComboBox2=ttk.Combobox(parent, state="readonly", values=("I hate to see the bold text..", "ciao", "hola", "hello"), textvariable=SV2, width=50)
MenuComboBox2.bind("<FocusIn>", Defocus)
MenuComboBox2.place(x=20, y=60)

parent.mainloop()

它起作用,但一点也不起作用,在我看来,它有一种“不良行为”。组合框小部件中的文本变为粗体,我不喜欢它(请参阅我附加的GIF)。我有两个问题:

  1. 如何改进我的自定义“散焦”功能,以取消组合框小部件中的“粗体选项”

  2. 有没有办法更改组合框小部件的默认样式以删除焦点和粗体文本选项?通过这种方式,我可以避免每次必须使用ComboBox小部件时都使用自定义函数

enter image description here


Tags: thetotext部件parentttkboldset
1条回答
网友
1楼 · 发布于 2024-09-29 23:26:52

Combobox在其条目聚焦时使用粗体文本。因此,一个解决方案是使用另一个条目,并将焦点转向它。
所以我创建了一个名为dump的伪条目。这个转储通过place_forget()隐藏。
如何转移注意力? 为此,每当选择项目时<<ComboboxSelected>>运行此步骤

  • 聚焦根窗口(parent.focus()
  • 在条目中键入内容(set()
  • 聚焦它(focus()
  • 选择它select_range()

为了了解差异,我加入了普通组合框MenuComboBox2

from tkinter.ttk import Combobox
from tkinter import *
class CBox(Frame):
    def __init__(self,parent,variable):
        super().__init__(parent)
        self.SV=variable
        self.Box=Combobox(self,state="readonly", values=("I hate to see the bold text..", "ciao", "hola", "hello"), textvariable=self.SV, width=50)
        self.Box.bind('<<ComboboxSelected>>',self.doThat)
        self.fvar=StringVar()
        self.fake=Entry(self,text='test',textvariable=self.fvar)
        self.arrange()
    def arrange(self):
        self.Box.pack()
        self.fake.pack()
        self.fake.pack_forget()
    def doThat(self,*args):
        self.focus()
        self.fvar.set('Hello')
        self.fake.focus()
        self.fake.select_range(0,'end')
root=Tk()
SV=StringVar()
def Defocus(event):
    event.widget.master.focus_set()
diff=Combobox(root,state="readonly", values=("I hate to see the bold text..", "ciao", "hola", "hello"), width=50)
diff.pack()
diff.bind("<FocusIn>", Defocus)
a=CBox(root,SV)
a.pack()

root.mainloop()

编辑:现在它不依赖于父元素。(仅指CBox

相关问题 更多 >

    热门问题