簡體   English   中英

如何更改 Tkinter 中 Frame 的背景?

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

我一直在 Python 3.3 中使用 Tkinter 創建一個Email程序。 在各種網站上,我看到 Frame 小部件可以使用Frame.config(background="color")獲得不同的背景。 但是,當我在 Frames 中使用它時,會出現以下錯誤:

_tkinter.TclError: unknown option "-Background"

執行以下操作時它不起作用:

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

或者:

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

我想不通。 我會發布我的整個源代碼,但我不希望它暴露在 inte.net 上,但框架的創建是這樣的:

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

我嘗試了多種嘗試修改背景的選項。 該框架就像環繞收件箱的 email 預覽。

如果需要,這是我導入模塊的方式:

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

解決了。 謝謝,它是右邊的收件箱欄。 背景需要是白色的。 對結果滿意,讓我們處理收件箱滾動。

這個問題的根源是,你在不知不覺中使用的Frame從類ttk包,而不是從tkinter包。 來自ttk不支持后台選項。

這是您不應該進行全局導入的主要原因 - 您可以覆蓋類和命令的定義。

我建議做這樣的導入:

import tkinter as tk
import ttk

然后使用tkttk為小部件添加前綴:

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

然后,您可以立即明白您正在使用哪個小部件,而不僅僅是更多的打字。 如果你這樣做了,代碼中的這個錯誤永遠不會發生。

你使用ttk.Framebg選項不起作用。 您應該創建樣式並將其應用於框架。

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()

謝謝你的回答。 正如你所說的,我已經導入了 Tkinter * 並且實際上還明確地從 tkinter 導入了 Frame 而沒有意識到這一點。 所以理論上它應該有效,但實際上我使用過 LabelFrame,再次沒有考慮,這就是它不起作用的原因。 在導入中添加了 LableFrame 並且運行良好。 非常感謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM