【问题标题】:how to add color to ttk module widgets?如何为 ttk 模块小部件添加颜色?
【发布时间】:2017-12-01 08:45:42
【问题描述】:

如何为 ttk 模块中的小部件添加 bg 颜色?,波纹管没有给我所需的结果。 我尝试了作为 Tkinter 模块的常用方法。但它没有用。

from tkinter import *
from tkinter.ttk import *
import sqlite3

db_obj = sqlite3.connect("contact.db")
def count_index():
    cur = db_obj.cursor()
    count = cur.execute("select count(index) from contacts;")
    rowcount = cur.fetchone()[0]
    return rowcount

def enter(event=None):
    x=e1.get()
    y=e2.get()
    ci=count_index()+1
    db_obj.execute("insert into contacts(index, name, number) 
values(?,?,?);",(ci,x,y))
    db_obj.commit()


fx =Frame(bg="LightCyan2")
bt=Button(fx)
fr.pack(expand=YES)
l1=Label(fx, text="Enter name", bg="LightCyan2").grid(row=1,column=1)
l2=Label(fx, text="Enter number", bg="LightCyan2").grid(row=2,column=1)
e1=Entry(fx)
e2=Entry(fx)
e1.grid(row=1,column=2)
e2.grid(row=2,column=2)
e1.focus()
e2.focus()
bt.config(text="ENTER",command=enter)
bt.grid(row=3,column=2)
bt.bind('<Return>',enter)

fx.mainloop()

【问题讨论】:

  • 欢迎来到StackOverflow,请在提问时更具体一点:到目前为止,您对代码示例进行了哪些尝试? / 您有什么期望? / 您遇到什么错误? *请查看“How to ask”以获得帮助

标签: python-3.x tkinter ttk


【解决方案1】:

您需要使用样式对象来为小部件添加颜色。 单独定义样式对象,并在标签中使用样式名称来获取所需的样式。

s1 = Style()
s1.configure('My.Frame', background='LightCyan2')

修改代码:

from tkinter import *
from tkinter.ttk import *
import sqlite3

db_obj = sqlite3.connect("contact.db")
def count_index():
    cur = db_obj.cursor()
    count = cur.execute("select count(index) from contacts;")
    rowcount = cur.fetchone()[0]
    return rowcount

def enter(event=None):
    x=e1.get()
    y=e2.get()
    ci=count_index()+1
    conx.execute("insert into words(index, name, number) values(?,?,?);",(ci,x,y))
   conx.commit()


s1 = Style()
s1.configure('My.Frame', background='LightCyan2')

s2=Style()
s2.configure('My.Label', background='LightCyan2')

fx =Frame(style='My.Frame')
bt=Button(fx)
fx.pack(expand=YES)
l1=Label(fx, text="Enter word", style='My.Label').grid(row=1,column=1)
l2=Label(fx, text="Enter meaning", style='My.Label').grid(row=2,column=1)
e1=Entry(fx)
e2=Entry(fx)
e1.grid(row=1,column=2)
e2.grid(row=2,column=2)
e1.focus()
e2.focus()
bt.config(text="ENTER",command=enter)
bt.grid(row=3,column=2)
bt.bind('<Return>',enter)

fx.mainloop()

我想这可以解决你的问题,虽然我不确定这是否是你要问的。

【讨论】:

  • 是的,Hille 是对的,也许您应该指出导致问题的确切代码行而不是整个代码。
  • 下次我会这样做,非常感谢您的帮助。
猜你喜欢
  • 2013-04-20
  • 2014-07-08
  • 2020-10-18
  • 2023-02-23
  • 2011-05-06
  • 2011-04-30
  • 2020-11-22
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多