如何更改Tkinter中帧的背景?

2024-06-06 05:17:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用Python 3.3中的Tkinter创建一个电子邮件程序。 在不同的站点上,我看到Frame小部件可以使用Frame.config(background="color")获得不同的背景。 但是,当我在帧中使用此选项时,会出现以下错误:

_tkinter.TclError: unknown option "-Background"

执行以下操作时不起作用:

frame = Frame(root, background="white")

或:

frame = Frame(root)
frame.config(bg="white")

我想不出来。 我会发布我的全部源代码,但我不希望它在互联网上公开,但框架的创建过程如下:

mail1 = Frame(self, relief=SUNKEN)
mail1.pack()
mail1.place(height=70, width=400, x=803, y=109)
mail1.config(Background="white")

我尝试了多种方法来修改背景。框架就像是收件箱的电子邮件预览的环绕。

如果需要的话,我用这种方式导入我的模块:

import tkinter, time, base64, imaplib, smtplib
from imaplib import *
from tkinter import *
from tkinter.ttk import *

以下是完整的回溯:

Traceback (most recent call last):
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 457, in <module>
main()
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 453, in main
app = Application(root) #start the application with root as the parent
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 60, in __init__
self.initINBOX()
File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 317, in initINBOX
mail1.config(bg="white")
File "C:\Python33\lib\tkinter\__init__.py", line 1263, in configure
return self._configure('configure', cnf, kw)
File "C:\Python33\lib\tkinter\__init__.py", line 1254, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-bg"

回答中的代码出现以下错误:

  File "C:\Users\Wessel\Dropbox\Python\Main\Class Ginomail.py", line 317, in initINBOX
  mail1 = Frame(self, relief=SUNKEN, style='myframe')
  File "C:\Python33\lib\tkinter\ttk.py", line 733, in __init__
  Widget.__init__(self, master, "ttk::frame", kw)
  File "C:\Python33\lib\tkinter\ttk.py", line 553, in __init__
  tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "C:\Python33\lib\tkinter\__init__.py", line 2075, in __init__
  (widgetName, self._w) + extra + self._options(cnf))
  _tkinter.TclError: Layout myframe not found

解决了!谢谢。右边的收件箱栏,背景必须是白色。 Happy with the results, lets work on that inbox scrolling.


Tags: inpyselfinitmaintkinterlineframe
2条回答

使用ttk.Framebg选项对其不起作用。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()

问题的根源在于,您在不知不觉中使用了ttk包中的Frame类,而不是tkinter包中的Frame类。来自ttk的不支持后台选项。

这是不应该进行全局导入的主要原因——可以覆盖类和命令的定义。

我建议像这样导入:

import tkinter as tk
import ttk

然后用tkttk作为小部件的前缀:

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

然后,你使用的是哪一个小部件就变得很明显了,只需再多输入一点就可以了。如果这样做了,代码中的这个错误就不会发生。

相关问题 更多 >