我创建了一个继承自标准Button的自定义Tkinter Button小部件,纯粹出于审美目的,因此我可以在整个程序中重复相同的样式,而无需每次都手动配置它。我的自定义按钮的代码在这里:
import tkinter as tk
class gameButton(tk.Button):
def __init__(self,*args,**kwargs):
super(gameButton,self).__init__()
self.root=args[0]
self.configure(text=kwargs["text"])
self.configure(fg=kwargs["fg"],
activeforeground=kwargs["fg"])
try:
self.configure(command=kwargs["command"])
except KeyError:
pass
self.configure(relief="flat",cursor="hand2")
self.bind("<Enter>",self.hover)
self.bind("<Leave>",self.leave)
self.old=kwargs["bg"]
self.dark=self.darken(self.old)
self.configure(bg=self.old,activebackground=self.dark,
bd=1,relief="solid")
def getRGB(self,h):
it=tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
return it
def getHex(self,h):
it='#%02x%02x%02x' % h
return it
def darken(self,h):
currentHex=self.old.replace("#","")
currentRGB=self.getRGB(currentHex)
currentR=currentRGB[0]
currentG=currentRGB[1]
currentB=currentRGB[2]
if currentR>30:
newR=round(currentR-30)
else:
newR=0
if currentG>30:
newG=round(currentG-30)
else:
newG=0
if currentB>30:
newB=round(currentB-30)
else:
newB=0
newRGB=(newR,newG,newB)
newHex=self.getHex(newRGB)
return newHex
def hover(self,event):
self.configure(bg=self.dark)
def leave(self,event):
self.configure(bg=self.old)
我试图在框架中将它们网格化的代码部分在这里(我将gameButton导入为GB):
game=Frame(notebook,bg=bg)
notebook.add(game,text="Game")
mapb=GB(game,text="Map",compound="left",bg=bg,fg=fg)
travelb=GB(game,text="Travel",compound="left",bg=bg,fg=fg)
bagb=GB(game,text="Bag",compound="left",bg=bg,fg=fg)
pokedexb=GB(game,text="Pokédex",compound="left",bg=bg,fg=fg)
partyb=GB(game,text="Party",compound="left",bg=bg,fg=fg)
saveb=GB(game,text="Save",compound="left",bg=bg,fg=fg)
mapb.grid(row=0,column=0,padx=5,pady=5,sticky="nesw")
travelb.grid(row=0,column=1,padx=5,pady=5,sticky="nesw")
bagb.grid(row=0,column=2,padx=5,pady=5,sticky="nesw")
pokedexb.grid(row=1,column=0,padx=5,pady=5,sticky="nesw")
partyb.grid(row=1,column=1,padx=5,pady=5,sticky="nesw")
saveb.grid(row=1,column=2,padx=5,pady=5,sticky="nesw")
结果如下:
按钮在正常的根窗口中很好地网格,但它拒绝在根内的Frame内正常运行。