帧bg颜色未显示在tkinter窗口中



我正在尝试在tkinter窗口上显示一个颜色为#2231303的框架。框架的内容(一些进度条(正在显示,没有问题,但框架的颜色没有显示。该链接显示了窗口的相关部分的外观。https://drive.google.com/file/d/1VHYW0t9UhjMUeNbwFijkrIy6RiToN0BN/view?usp=sharing正如你所看到的,边框颜色没有被显示,也没有像我希望的那样完全填充宽度屏幕。没有任何错误,所以我完全空白。我四处寻找解释,但找不到任何解释。这些是我的代码的相关部分''

from tkinter import *
from tkinter.ttk import *
root = Tk()                            
root.title("Game") 
root.geometry("1280x720")
root["bg"] = "gray"
style = Style()

"''

def qn_func(self,qn_num,iteration) :
Game.clear(self)
global bar1,bar2,bar3,bar4
style.configure("var.TFrame",bg="#231303")
frame = Frame(root,height=120,width=1280,style="var.TFrame")
frame.grid(row=0,column=0,sticky=W+E+N)

"这里,bar1、bar2、bar3和bar4是我在框架内显示的进度条。事实上,我对国际米兰很陌生,所以请尽量保持简单。我还尝试在测试文件中只显示框架及其内容,这次显示了颜色,但框架宽度的问题仍然存在。有人知道为什么会发生这种事吗?如果有人能告诉我为什么会发生这种事,那将是一个很大的帮助。我还在代码中使用tkinter.ttk。

也许您想考虑一个更可靠的OOP实现。

#don't pollute your namespace
import tkinter as tk
import tkinter.ttk as ttk
from dataclasses import dataclass, asdict

#create a "struct" to default to that represents ALL options for the widget
@dataclass
class Frame_dc:  
background:  str = 'black'
bordercolor: str = 'black' 
darkcolor:   str = 'black'
lightcolor:  str = 'black'
relief:      str = 'flat'

#prepare your data
HeaderFrame = asdict(Frame_dc(*['#231303']*4)) #overwrite the first 4 vars with your custom color
ErrorFrame  = asdict(Frame_dc(*['red']*4))

#wrap all your styles in a custom theme 
class CustomTheme(ttk.Style):
def __init__(self, basetheme='clam'):
ttk.Style.__init__(self)

#slim example
self.theme_create('custom', basetheme, {
'custom.TFrame': {
'configure': HeaderFrame,
},
'error.TFrame': {
'configure': ErrorFrame,
},
#add more custom styles here
#see: https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Style.theme_create
})
self.theme_use('custom')

#extend your root
class App(tk.Tk):
#define application constants
WIDTH  = 1280
HEIGHT = 720
TITLE  = 'Game'
def __init__(self, **kwargs):
tk.Tk.__init__(self, **kwargs) #be more specific than "super()"
CustomTheme()

self.configure(bg="gray")

#name things what they are
self.header = ttk.Frame(self, height=120, style="custom.TFrame")
self.header.grid(row=0, column=0, sticky='wen')

#make `self.frame` fill width ~ 
#technically this is making the entire column fill the width
#but only because there is no other column with weight to disperse
self.grid_columnconfigure(0, weight=1)

#properly initialize your app
if __name__ == '__main__':
app = App()
app.title(App.TITLE)
app.geometry(f'{App.WIDTH}x{App.HEIGHT}')
app.mainloop()

旁白:

远离global。我想不出有哪种语言global是一件好事,而且我知道很多语言。一个好的设计模式实现了encapsulationglobalencapsulation的对立面。global也可以被视为强制依赖,具体取决于上下文。然后你就有了整个问题:如果我要破解你的游戏,你就把所有的勇气都留给了我。如果你有一个好的设计,你可能在余生中永远不要使用global,而不会在功能和访问方面做出任何牺牲。

最新更新