You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter中score变量局部未赋值报错问题求助

Fixing the "Local Variable Referenced Before Assignment" Error in Your Tkinter Flashcard App

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:

  1. 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...
    
  2. Add global score to 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 - 1
    
  3. Bonus Fix: A Tiny Typo in Your Maths Function
    I spotted a mistake in your maths() function—your confirm button calls checkcorrectcs() (the computer science check function) instead of checkcorrectmaths(). 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 ![Image Alt Text](image-url) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:22:56