ttk Entry background colour

后端 未结 3 1816
暖寄归人
暖寄归人 2020-12-16 03:31

How exactly do I change the background colour of an Entry widget from ttk? What I have so far is:

        self.estyle = ttk.Style()
        self.estyle.confi         


        
3条回答
  •  再見小時候
    2020-12-16 04:07

    I liked your approach in using an image, but I think it's a tad tedious to go through the process of importing an image as a base64 encoded string when PhotoImage allows for creating images on the fly. I've expanded on the concept to make a class that handles making such an 'image' to use as a border, and it takes any arguments a regular ttk.Entry widget would. Note that I'm only able to test on Windows 10, but this should be platform independent.

    from tkinter import ttk
    import tkinter as tk
    
    class BorderedEntry(ttk.Entry):
        def __init__(self, root, *args, bordercolor, borderthickness=1,
                     background='white', foreground='black', **kwargs):
            super().__init__(root, *args, **kwargs)
            # Styles must have unique image, element, and style names to create
            # multiple instances. winfo_id() is good enough
            e_id = self.winfo_id()
            img_name = 'entryBorder{}'.format(e_id)
            element_name = 'bordercolor{}'.format(e_id)
            style_name = 'bcEntry{}.TEntry'.format(e_id)
            width = self.winfo_reqwidth()
            height = self.winfo_reqheight()
            self.img = tk.PhotoImage(img_name, width=width, height=height)
            self.img.put(bordercolor, to=(0, 0, width, height))
            self.img.put(background, to=(borderthickness, borderthickness, width -
                         borderthickness, height - borderthickness))
    
            style = ttk.Style()
            style.element_create(element_name, 'image', img_name, sticky='nsew',
                                 border=borderthickness)
            style.layout(style_name,
                         [('Entry.{}'.format(element_name), {'children': [(
                          'Entry.padding', {'children': [(
                              'Entry.textarea', {'sticky': 'nsew'})],
                              'sticky': 'nsew'})], 'sticky': 'nsew'})])
            style.configure(style_name, background=background,
                            foreground=foreground)
            self.config(style=style_name)
    
    root = tk.Tk()
    bentry_red = BorderedEntry(root, bordercolor='red')
    bentry_blue = BorderedEntry(root, bordercolor='blue')
    bentry_red.grid(row=0, column=0, pady=(0, 5))
    bentry_blue.grid(row=1, column=0)
    root.mainloop()
    

提交回复
热议问题