【问题标题】:How to change ttk.Entry insertion cursor color?如何更改 ttk.Entry 插入光标颜色?
【发布时间】:2020-12-01 10:34:50
【问题描述】:

我正在使用 Python3 和 tkinter 8.6 开发应用程序。其中一部分是一个相当复杂的对话框,它使用深色背景。随附的代码仅使用几个小部件来显示我无法工作的区域。除其他外,我的对话框使具有键盘焦点的小部件变得明显(通过突出显示的背景颜色,只是选项卡)。 我已经尝试了所有可能的搜索字符串来寻找解决方案,但无济于事。原来 'insertwidth': '4' 确实有效。我想要做的是更改 ttkEntry 小部件插入点光标的颜色。我发现的建议答案似乎都不是解决方案。提前致谢。

    #!/usr/bin/env python3
import tkinter as tk
import tkinter.ttk as ttk    # ttk widgets use styles
import tkinter.font as tkfont

def app_exit():
    root.destroy()


root = tk.Tk()
root.geometry('400x50+400+100')
bg = '#2C2B3B'    # dark blue
hlbg = '#3F3D5C'  # dark blue a shade lighter
fg = 'white'
ebg = 'pink'   # Entry inserts
root.configure(background=bg)  # fills in around labels and entries
font14 = tkfont.Font(size=14)
font10 = tkfont.Font(size=10)
root.option_add('*TEntry*Font', font14)
ttstyle = ttk.Style()
ttstyle.theme_use('default')
ttstyle.theme_settings('default', {
    '.': {   # this sets the general defaults for everybody
        'configure': {'font': font14, 'background': bg, 'foreground': fg}},
    'TButton': {
        'map': {'background': [('active', hlbg), ('focus', hlbg), ('!disabled', bg)]}},
    'TEntry': {  # 'insertforeground' and 'insertforeground' does not seem to do anything
        'configure': {'insertwidth': '4', 'insertforeground': ebg, 'insertforeground': ebg},
        'map': {'fieldbackground': [('active', hlbg), ('focus', hlbg), ('!disabled', bg)],
                'foreground': [('!disabled', fg)]}},
    'TLabel': {
        'configure': {'font': font10}}})

lbl1 = ttk.Label(root, text='Hello ')
tbx = ttk.Entry(root)
btnOK = ttk.Button(root, text='Exit', command=app_exit)

lbl1.grid(row=0, column=0, sticky='w')
tbx.grid(row=0, column=1, sticky='ew')
btnOK.grid(row=0, column=2, sticky='e')
tbx.insert(0,'AbCdEf')
tbx.focus()

root.mainloop()

Example output

【问题讨论】:

  • 您只想改变插入光标的颜色,对吗?使这条线像tbx = ttk.Entry(root,insertbackground='red')
  • 这是我尝试过的许多事情之一,但不起作用(至少在我的 Ubuntu 系统上)。其中一个插入前景应该是背景。 (我补充说,作为我后来尝试的一个例子,并犯了一个编辑错误。你的建议在我的系统上出现了一个错误:文件“/usr/lib/python3.8/tkinter/__init__.py”,第 2567 行,在 init self.tk.call(_tkinter.TclError: 未知选项“-insertbackground”
  • @CoolCloud: ttk 条目没有那个选项。
  • 好吧,请注意,说tk.Entry()而不是ttk.Entry(...)

标签: python-3.x tkinter color-scheme tkinter-entry insertion


【解决方案1】:

ttk Entry 小部件的选项是insertcolor。

...
'TEntry': {
    'configure': {..., 'insertcolor': ebg},
...

这里是 ttk 小部件所有选项的方便参考。它在 tcler 的 wiki 上,因此语法是 tcl 而不是 python,但选项名称本身在语言之间是相同的。

Changing Widget Colors

【讨论】:

  • Bryan 非常感谢你,它有效,你永远不会相信我花了多少时间在这上面。感谢您回答我的下一个问题。你就是男人!
  • 我赞成你作为参考。我用了别的东西,但是你发布的那个更好。
猜你喜欢
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 2012-07-23
  • 1970-01-01
  • 2010-10-20
  • 2012-07-16
相关资源
最近更新 更多