How do I change the background of a Frame in Tkinter?

后端 未结 2 1672
你的背包
你的背包 2020-11-30 13:40

I have been creating an Email program using Tkinter, in Python 3.3. On various sites I have been seeing that the Frame widget can get a different background using <

相关标签:
2条回答
  • 2020-11-30 13:57

    You use ttk.Frame, bg option does not work for it. You should create style and apply it to the frame.

    from tkinter import *
    from tkinter.ttk import * 
    
    root = Tk()
    
    s = Style()
    s.configure('My.TFrame', background='red')
    
    mail1 = Frame(root, style='My.TFrame')
    mail1.place(height=70, width=400, x=83, y=109)
    mail1.config()
    root.mainloop()
    
    0 讨论(0)
  • 2020-11-30 14:20

    The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

    This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

    I recommend doing imports like this:

    import tkinter as tk
    import ttk
    

    Then you prefix the widgets with either tk or ttk :

    f1 = tk.Frame(..., bg=..., fg=...)
    f2 = ttk.Frame(..., style=...)
    

    It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

    0 讨论(0)
提交回复
热议问题