python.variable +=1在turtle中没有正常工作

wqnecbli  于 2022-10-30  发布在  Python
关注(0)|答案(2)|浏览(151)

我试图做一些像“点击器”上的按钮为2人的,但我的变量+=1是不工作,在这个程序。我的代码:

from tkinter import *
import turtle
wn = turtle.Screen()
wn.title("Pong by Daniel")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
score_a = 0
score_b = 0

pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 240)
pen.write("a:0  b: 0", align="center", font=("Courier", 24, "normal"))

button_a = Button( text="a")
button_a.place(x=530, y=300)
button_b = Button( text="b")
button_b.place(x=130, y=300)

def button_a():
     score_a+= 1
     pen.clear()
     pen.write("a:{}  b: {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal"))
def button_b():
     score_b += 1
     pen.clear()
     pen.write("a:{}  b: {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal"))

while True:
     wn.update()    
     turtle.onclick(button_a)
     turtle.onclick(button_b)

我不能把这些变量放在def中,bcs它会一直重置(我想),有人对此有什么想法和意见吗?我是编程新手,需要学习很多东西。
我试过在没有def的情况下使用它,但我在使用turtle.onclick时需要它,我不知道如何从这一点上移动。

u5rb5r59

u5rb5r591#

variable += 1没有问题。它不工作是因为作用域问题,并且没有定义命令到按钮。试试这个:

from tkinter import *
import turtle

wn = turtle.Screen()
wn.title("Pong by Daniel")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
score_a = 0
score_b = 0

pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 240)
pen.write("a:0  b: 0", align="center", font=("Courier", 24, "normal"))

def button_a_1():
   print("hello")
   global score_a
   score_a += 1
   pen.clear()
   pen.write("a:{}  b: {}".format(score_a, score_b), 
   align="center", font=("Courier", 24, "normal"))

def button_b_1():
   global score_b
   score_b += 1
   pen.clear()
   pen.write("a:{}  b: {}".format(score_a, score_b), 
   align="center", font=("Courier", 24, "normal"))

button_a = Button(text="a", command=button_a_1)
button_a.place(x=530, y=300)
button_b = Button(text="b", command=button_b_1)
button_b.place(x=130, y=300)

while True:
   wn.update()
   turtle.onclick(button_a_1)
   turtle.onclick(button_b_1)
nue99wik

nue99wik2#

当您呼叫Button_a时,请执行下列动作:

def button_a(value):
   value += 1
   pen.clear()
   pen.write("a:{}  b: {}".format(score_a, score_b), align="center", font=("Courier", 24, "normal"))

button_a(score_a)

相关问题