如何解决所有按钮框和文本均为黑色
又是我...
由于最近的问题一直在讨论中,因此我正在为游戏制作主菜单导航。一切都进展顺利,直到最近的一个错误使所有文本(在按钮中或仅在屏幕上绘制)变成黑色。我不确定为什么会这样,我希望有人比我聪明。我真的很需要这样做,因此非常感谢您的帮助。
# Libraries #
import pygame # Imports the Pygame library.
from pygame.locals import * # Imports the Pygame Locals library.
import ResolutionMenu # Imports the ResolutionMenu file (must be stored in the same location as this file to work)
# Classes #
class GuiSettings: # Class used to define the colour and size of buttons.
def __init__(self):
self.TextSize = 26
self.button_color = (35,65,145)
self.button_color_hover = (70,105,150)
class Button():
def __init__(self,x,y,width,height,outline,settings,text = "",action = None): # Classes used to actually create a button.
self.x = x # Screen is divided into an axis,x being horizontal.
self.y = y # And Y being vertical. The maximum bound changes depending on screen resolution.
self.width = width # This determines the dimensions of the Box that is going to be created.
self.height = height # Height and Width are measured in pixels,similar to X and Y.
self.text = text # Allows text to be printed over the top of the button.
self.settings = settings # Allows it to be manipulated by the GuiSettings.
self.action = action # Will be used to determine what 'action' the user is performing on the button.
self.outline = outline # Will be used to determine if an outline is or is not drawn around the button.
def draw(self,screen,outline = None):
if self.outline: # Used to draw a black outline around the perimeter of the square.
pygame.draw.rect(screen,self.outline,(self.x - 2,self.y - 2,self.width + 4,self.height + 4),0)
if self.text != "":
font = pygame.font.SysFont('segoeuisemibold',self.settings.TextSize) # Settings for text inside of the button Box.
text = font.render(self.text,1,(0,0)) # Renders the font with the variables 'text' which is the text on the Box,anti-aliasing is the second
# option,of which removes the jagged effect that might appear around the Box.
# and finally the colour of the outline.
screen.blit(text,(self.x + (self.width / 2 - text.get_width() / 2),self.y + (self.height / 2 - text.get_height() / 2))) # Places the text in the middle of the Box.
def update(self,events): # Simply used to determine what actions need to be taken when the button is pressed,if any.
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and self.isOver(pygame.mouse.get_pos()) and self.action:
self.action()
def isOver(self,pos): # Determines if the cursor is actually over the button Box or not.
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
# Variables #
settings = GuiSettings() # Assigning class to variable to access parameters.
H,W = ResolutionMenu.resolution # Splits the tuple value of resolution into individual segments and assigns them their respective variables.
pygame.init() # Initialises the pygame library.
pygame.display.set_caption("Main Menu") # Creates a title for the program.
font = pygame.font.SysFont(None,settings.TextSize) # Sets the default font to that of the font on the System. Allows for cross platform usability.
screen = pygame.display.set_mode((ResolutionMenu.resolution)) # Sets the resolution to the resolution determined in ResolutionMenu.py.
# Functions #
def draw_text_center(text,font,colour,surface):
textobj = font.render(text,colour) # Function for simple text creation. No button surrounding.
textrect = textobj.get_rect() # Creates a font taking the string 'text',sets antialiasing to true and sets the text colour.
textrect.center = ((H / 2),(W / 10)) # Creates a rectangle around 'textobj' which is simply the text.
surface.blit(textobj,textrect) # Finds the center of the screens
def draw_text(text,surface,XandY): # Same function as above but with manipulatable positioning.
textobj = font.render(text,colour)
textrect = textobj.get_rect()
textrect.topleft = (XandY)
surface.blit(textobj,textrect)
def MainMenu():
global font
while True:
pygame.display.set_mode((H,W)) # Sets the resolution to the resolution chosen before.
pygame.display.flip() # Updates the surface display.
buttons = [
Button(W / 10,H / 5,W / 3,H / 15,0),"Start Simulation",lambda: game()),# Buttons that will be displayed are placed inside of a list.
Button(W / 10,H / 2,"Options Menu",lambda: OptionsMenu()) # Lambda functions are one time use functions without names. This allows each
] # button to have a single use function that directs the program to the specified section.
running = True
while running:
events = pygame.event.get() # Gathers all events (user made inputs) that Could occur.
for event in events:
if event.type == pygame.QUIT: # When the X is pressed in the corner of the application,it shall close.
pygame.quit()
return
if event.type == KEYDOWN: # When pressing Esc the function is broken and refreshes.
if event.key == K_ESCAPE:
running = False
for button in buttons:
button.update(events) # Enables the button to be interacted with.
screen.fill((100,100,100)) # Creates a grey background.
draw_text_center("Main Menu Navigation",screen) # Creates Main Menu Navigation text in the top middle of the screen.
font = pygame.font.SysFont(None,settings.TextSize) # Makes the font size equal to that of settings.TextSize from GuiSettings class.
for button in buttons:
button.draw(screen) # Draws the buttons on the window.
pygame.display.flip() # Updates the surface display again.
pygame.display.update() # Updates a portion of the screen,allowing for text to render.
def game():
running = True
while running:
screen.fill((100,100))
draw_text_center("Simulation Navigation",screen)
buttons = [
Button(W / 10,"Enter Simulation",lambda: FileTraversal()),Button(W / 10,"Instructions",lambda: Instructions())
]
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
for button in buttons:
button.update(events)
for button in buttons:
button.draw(screen)
pygame.display.flip()
pygame.display.update()
def Instructions():
running = True
while running:
screen.fill((100,100))
draw_text("This is the simulation manual.",(50,50))
draw_text("There are a few button combinations that will perform different tasks:",100))
draw_text("P",(200,150))
draw_text(": Pauses the simulation.",(70,150))
draw_text("D",200))
draw_text(": Toggles drawing mode. Allows for faster computation.",200))
draw_text("F",250))
draw_text(": Toggles the display of food. Increases FPS.",250))
draw_text("+ and -",300))
draw_text(": Increases or Decreases the speed of the simulation. FPS impact.",(130,300))
draw_text("Middle Mouse Click",350))
draw_text(": Zoom in and out.",(250,350))
draw_text("Right Mouse Click",400))
draw_text(": Pan around the environment",(240,400)) # All of these are displayed on the screen as instructions for the user.
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
pygame.display.flip()
pygame.display.update()
def FileTraversal():
import os # Imports the Operating System library that allows for command line execution.
import platform # Imports the Platform library that allows for system analysis.
p = platform.system() # Assign the variable p the name of the operating system.
if p == "Linux":
os.chdir('/home/CHANGE/Desktop/School Work/New') # Directory traversal.
pygame.display.iconify() # Linux systems do not run EXE's. This file is an ELF file
os.system('./mygame') # and so must be run from terminal.
if p == "Windows":
os.chdir('C:/Users/CHANGE/Desktop/Project/') # Directory traversal.
# Uses EXE's as ELF's require Linux kernals.
if p == "OSX":
None
def OptionsMenu():
global settings # Functions use local variables. In order to manipulate the global value,global settings is specified.
pygame.display.set_mode((800,600))
buttons = [
Button(100,150,250,50,"Set Text Size: Small",lambda: settings.__setattr__('TextSize',24)),# Button uses a lambda function to access
Button(450,"Set Text Size: Regular",26)),# the attributes of settings,which is the class
Button(100,300,"Set Text Size: Large",28)),# GuiSettings. It then sets the value of TextSize to
Button(450,"Set Text Size: Larger",30)) # the corresponding value,depending on the button pressed.
]
running = True
while running:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
pygame.display.set_mode((ResolutionMenu.resolution)) # Bug fix. Returns the resolution to the prevIoUsly selected.
for button in buttons:
button.update(events)
screen.fill((100,100))
for button in buttons:
button.draw(screen)
pygame.display.flip()
MainMenu()
# Libraries #
from tkinter import *
import time
# Variables List #
root = Tk() # Initialises Tkinter under the variable 'root'.
root.title("Resolution") # Applies a name to the window.
root.geometry("230x200") # Sets the window's geometry.
displays = 800,600,1024,786,1280,1600,1200,1920,1080 # Uses a string for resolutions.
running = True
v = Intvar() # Assignes the value of V to be an integer.
# Functions #
def CONFIRM(label1):
global resolution # Global variables used to access / manipulate outside of function.
global selection
selection = v.get() # Takes the value from the radio buttons.
if selection == 1:
resolution = (displays[0:2]) # Iterative Index naviation. 0 (0) indicates the first index up until the 2nd (2),but not including (,index.
time.sleep(0.2) # Pauses the program for .2 seconds for fluid transition appearance.
root.destroy() # Closes the TK window as it is no longer needed.
elif selection == 2:
resolution = (displays[2:4])
time.sleep(0.2)
root.destroy()
elif selection == 3:
resolution = (displays[4:6])
time.sleep(0.2)
root.destroy()
elif selection == 4:
resolution = (displays[6:8])
time.sleep(0.2)
root.destroy()
elif selection == 5:
resolution = (displays[8:10])
time.sleep(0.2)
root.destroy()
else:
resolution = (displays[0:2])
time.sleep(0.2)
root.destroy()
# Radio Button Creation #
v.set(1) # Validation. Sets the variable of V to 1 (radiobutton1) automatically.
Radio1 = Radiobutton(root,font = "Veranda 10",text = "800 x 600",variable = v,value = 1).pack(anchor = W)
Radio2 = Radiobutton(root,text = "1024 x 768",value = 2).pack(anchor = W)
Radio3 = Radiobutton(root,text = "1280 x 1024",value = 3).pack(anchor = W)
Radio4 = Radiobutton(root,text = "1600 x 1200",value = 4).pack(anchor = W)
Radio5 = Radiobutton(root,text = "1920 x 1080",value = 5).pack(anchor = W)
# Each of the above create a radio button. Using Tkinter's pre-made Radiobutton() function,you can simply link
# the radio button to the necessary window,in this case "root",the font size and the desired text message
# a variable that will be used to hold the value of the selection,followed by an integer that will be stored
# inside of said variable. Finally we pack it using .pack() function and give it an anchor,ie the direction it is aligned.
label1 = Label(root,text="") # Temp variable to hold information for lambda expression.
b = Button(root,text = "Confirm",command = lambda:CONFIRM(label1)) # Lambda creates temporary in-line function to pass selection to Confirm()
b.pack(anchor = SE)
label1.pack()
# Program Loop #
mainloop()
解决方法
好吧!我解决了这个问题;原来我的“按钮”类中的某些代码行被意外删除。我备份了代码,并用工作版本替换了类之后,一切恢复正常。
固定的类代码将在底部。
感谢@ Nebulous29提出将轮廓值更改为(255,0,0)的建议。那实际上不是按钮的颜色,而是按钮周围的轮廓。更改后,我意识到大纲功能无法正常工作。
固定代码:
class Button():
def __init__(self,x,y,width,height,outline,settings,text = "",action = None):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.settings = settings
self.action = action
self.outline = outline
def draw(self,screen,outline = None):
if self.outline:
pygame.draw.rect(screen,self.outline,(self.x - 2,self.y - 2,self.width + 4,self.height + 4),0)
color = self.settings.button_color if not self.isOver(pygame.mouse.get_pos()) else self.settings.button_color_hover
pygame.draw.rect(screen,color,(self.x,self.y,self.width,self.height),0)
if self.text != "":
font = pygame.font.SysFont('segoeuisemibold',self.settings.TextSize)
text = font.render(self.text,1,(0,0))
screen.blit(text,(self.x + (self.width / 2 - text.get_width() / 2),self.y + (self.height / 2 - text.get_height() / 2)))
def update(self,events):
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and self.isOver(pygame.mouse.get_pos()) and self.action:
self.action()
def isOver(self,pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
,
黑色背景的问题出在创建按钮时:
Button(W / 10,H / 5,W / 3,H / 15,0),"Start Simulation",lambda: game()),# Buttons that will be displayed are placed inside of a list.
设置宽度和高度后,您将拥有(0,0)
,它将按钮的颜色设置为黑色。将其更改为(255,0)
之类的内容将导致背景为红色,文本为黑色(使按钮至少可读)。
我不确定为什么GuiSettings
中设置的按钮悬停颜色和按钮颜色没有更新按钮,但至少是暂时的修复
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。