通过“tab”键导航时,组合框前景色设置丢失

San*_*S D 5 tkinter python-3.x

当我通过“tab”键导航出组合框时,前台设置会丢失。当在组合框中使用“左”和“右”箭头键时也会发生这种情况。当我用“按钮”替换“条目”小部件时,不会出现此问题。我找不到任何此类问题的发布。如何解决这个问题?这是示例代码。

当选择“无效”时,前景色应为“红色”,直到选择“有效”。但事实并非如此。附截图。在此输入图像描述 在此输入图像描述

但是,当仅使用鼠标时,它可以工作。所以我怀疑它与组合框、条目、tab键组合有关。

环境:Python 3.9.6 Windows 21H1(内部版本19043.1165)

import tkinter as objTK
from tkinter import ttk as objTTK

# Combobox dropdown event handler
def HandlerValidate(objEvent):
    strValue = vCombobox.get()
    
    if strValue == "Invalid":
        objStyle = objTTK.Style()
        objStyle.map("myCombobox.TCombobox", selectforeground=[('readonly', '!focus', 'red'), \
                                                ('readonly', 'focus', 'red')])
        print("Invalid")
    else:
        objStyle = objTTK.Style()
        objStyle.map("myCombobox.TCombobox", selectforeground=[('readonly', '!focus', 'black'), \
                                                    ('readonly', 'focus', 'white')])        
        print("Valid")
    # End of if
# End of HandlerValidate()

objWindow = objTK.Tk()

objStyle = objTTK.Style()
objStyle.theme_use("clam")

# Set black foreground for entry of combobox
objStyle.map("TCombobox", selectforeground=[('readonly', '!focus', 'black')], \
            selectbackground=[('readonly', '!focus', '#DCDAD5')])

# Create style for combobox
objStyle = objTTK.Style()
objStyle.configure("myCombobox.TCombobox")

# Add combobox widget
vCombobox = objTK.StringVar()
objCombobox = objTTK.Combobox(master=objWindow, width=10, state="readonly", \
                    textvariable=vCombobox, style="myCombobox.TCombobox", values=["Valid", "Invalid"])
objCombobox.current(0)
objCombobox.bind("<<ComboboxSelected>>", HandlerValidate)
objCombobox.place(x=10, y=10)

# Add entry widget
txtEntry = objTK.Entry(master=objWindow, width=5)
txtEntry.place(x=10, y=40)

objWindow.bind("<Escape>", lambda _: objWindow.destroy())
objWindow.geometry("110x90")
objWindow.mainloop()
Run Code Online (Sandbox Code Playgroud)

acw*_*668 2

当您离开(聚焦)组合框时,使用的颜色将为foreground,而不是selectforegroundforeground所以你还需要配置:

def HandlerValidate(objEvent):
    strValue = vCombobox.get()

    if strValue == "Invalid":
        objStyle.map("myCombobox.TCombobox", selectforeground=[('readonly', 'red')],
                                             foreground=[('readonly', 'red')])
    else:
        objStyle.map("myCombobox.TCombobox",
                     selectforeground=[('readonly', '!focus', 'black'), ('readonly', 'focus', 'white')],
                     foreground=[('readonly', '!focus', 'black'), ('readonly', 'focus', 'white')])
    print(strValue)
Run Code Online (Sandbox Code Playgroud)