Reputation: 157
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?
import pygame
pygame.init()
display_w = 800
display_h = 600
white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)
def run():
print("Input your message: ")
msg = input()
print("Enter font size: ")
font_size = int(input())
display = pygame.display.set_mode((display_w, display_h))
pygame.display.set_caption("TextPos")
text_x = 0
text_y = 0
def message_to_screen(msg, color, font_size, x, y):
font = pygame.font.SysFont(None, font_size)
screen_text = font.render(msg, True, color)
display.blit(screen_text, [x, y])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
running = False
pygame.quit()
run()
if event.key == pygame.K_q:
print("Enter display width: ")
display_w = int(input())
print("Enter display height: ")
display_h = int(input())
running = False
message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
m_x, m_y = pygame.mouse.get_pos()
text_x = m_x
text_y = m_y
display.fill(white)
message_to_screen("X: %s" % m_x, black, 30, 10, 10)
message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
message_to_screen(msg, black, font_size, text_x, text_y)
message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)
pygame.display.update()
run()
Upvotes: 0
Views: 6674
Reputation: 3360
A strange way of accessing the variable. Let's say your module name is xyz. Then:
import xyz
def func():
xyz.display_w = 80
Upvotes: 1
Reputation: 50711
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
In your case, you are attempting to set variables in your function, so Python treats them as local variables.
To treat them as global variables, use the global
keyword when you locally define them to indicate you're referencing, and modifying, the values outside the function scope.
Upvotes: 1