Python Tkinter中score变量局部未赋值报错问题求助
Hey there! Let's get that score variable issue sorted out first—this is a super common gotcha with Python global variables, so you're not alone here. Then I'll quickly cover the image upload question for your Stack Overflow post.
The Core Score Variable Problem
Your error happens because you need to explicitly declare global score inside every function that modifies the score variable. Right now, you declared global score once at the top, but functions like scoreadd() and scoreminus() don't know they should use the global version of score—they try to create a local variable instead, which causes the "referenced before assignment" error when you try to do score = score + 1.
Step-by-Step Fix:
Move your global score declaration to a cleaner spot (after imports, for better code structure):
from tkinter import * from PIL import ImageTk, Image from random import randint import os # Declare global score here, after imports score = 0 root = Tk() # Rest of your code...Add
global scoreto every function that modifies the score:
Update your score-related functions like this to tell them to use the global variable:def score0(): global score score = 0 def scoreadd(): global score score = score + 1 def scoreminus(): global score score = score - 1Bonus Fix: A Tiny Typo in Your Maths Function
I spotted a mistake in yourmaths()function—your confirm button callscheckcorrectcs()(the computer science check function) instead ofcheckcorrectmaths(). Fix that line to get maths scoring working:# Correct this line in the maths() function confirm_button = Button(maths_window, text="Confirm", command=lambda: checkcorrectmaths(math_questions, random_number2))
Uploading Images to Your Stack Overflow Question
You don't need to attach a zip file! Stack Overflow lets you upload images directly when creating your question:
- When editing your post, look for the image icon in the toolbar (it looks like a picture frame).
- Click it, then select your PNG files from your computer—they'll be hosted automatically, and you can add alt text for accessibility.
- If you prefer markdown syntax, you can use
once the image is uploaded.
That should get your score system working properly. Don't stress about redundant code right now—focus on getting the core functionality up, then you can refactor later (like creating a single check function for all subjects instead of separate ones)!
内容的提问来源于stack exchange,提问作者The Rolling Derp

