我正在尝试根据函数中的dict
个字符串创建一个简单的接口。每个字符串用于显示文本和一个可单击的乌龟(使用onclick()
使该乌龟可单击)。这样一来,我可以单击乌龟,然后输入一些值。
但是,如果我理解正确的话,当函数完成通过字典的循环运行时,该循环应定义的所有变量都被重新定义为通过该循环的最后一个变量,即字典的最后一个元素。因此,onclick()
函数仅向我返回字典的最后一个元素。
有没有一种方法可以使一个onclick()
函数对字典的每个元素进行不同的反应/对应?我真的不想为字典的每个元素编写一堆onclick()
函数。我正在尝试学习更好的方法。
list_alunos={'joao': ['5', 'm'],'maria': ['5', 'm'],'lobo': ['5', 'm'],'mau': ['5', 'm']}
def caca(dictx,file):
import turtle
mes=file
vert=350
hor=-600
def got(t,x,y,d) :
t.penup()
t.goto(x,y)
t.pendown()
t.seth(d)
def text(t,text, size, color, pos1, pos2):
t.penup()
t.goto(pos1, pos2)
t.color(color)
t.begin_fill()
t.write(text, font=('Arial', size, 'normal'))
t.end_fill()
new_vert = vert
for key in dictx:
nome = key
if vert == -340:
new_vert = 350
new_hor = hor + 250
if vert!= -340:
new_vert= new_vert-30
new_hor = hor
txt_vert = new_vert - 15
txt_hor = new_hor + 20
screen = turtle.Screen()
width = 1200
height = 1500
turtle.screensize(width, height)
tnome = turtle.Turtle(shape='turtle')
tnome.color('pink')
textnome = turtle
tnome.speed('fastest')
textnome.speed('fastest')
text(textnome, '%s' %(nome), '20', 'pink', txt_hor,txt_vert)
got(tnome,new_hor,new_vert,0)
def tnome_handler(x, y):
pos = list(dictx.keys()).index(nome)
listt = list(dictx)
pnt = screen.textinput(' pontuação', '%s: '%(listt[pos]))
pnt = [int(x) for x in pnt.split()]
if len(pnt) == 5 :
with open('%s.py' %(mes), 'a') as fd:
fd.write('\n%s.pontuacao(%i,%i,%i,%i,%i)' % (nome,pnt[0],pnt[1],pnt[2],pnt[3],pnt[4]))
tnome.color('blue')
tnome.onclick(tnome_handler)
caca(list_alunos,'mm')
答案 0 :(得分:1)
我相信以下代码重做可以实现您想要的。它有效地为每个唯一响应的乌龟/按钮生成了一个自定义处理程序:
from turtle import Screen, Turtle
WIDTH, HEIGHT = 1200, 1500
dict_alunos = {'joao': ['5', 'm'], 'maria': ['5', 'm'], 'lobo': ['5', 'm'], 'mau': ['5', 'm']}
def text(t, text, size, color, x, y):
t.penup()
t.goto(x + size, y - size/2)
t.color(color)
t.write(text, align='left', font=('Arial', str(size), 'normal'))
t.goto(x, y)
def caca(dictionary, mes):
def tnome_handler(nome, turtle, x, y):
pnt = screen.textinput('pontuação', '%s: ' % (nome))
pnt = [int(x) for x in pnt.split()]
if len(pnt) == 5:
with open('%s.py' % (mes), 'a') as fd:
fd.write('s.pontuacao(%i, %i, %i, %i, %i)\n' % (nome, pnt[0], pnt[1], pnt[2], pnt[3], pnt[4]))
turtle.color('blue')
vert = 350
hor = -600
new_vert = vert
for nome in dictionary:
if vert == -340:
new_vert = 350
new_hor = hor + 250
if vert != -340:
new_vert = new_vert - 30
new_hor = hor
txt_vert = new_vert - 15
txt_hor = new_hor + 20
turtle = Turtle(shape='turtle')
turtle.color('pink')
turtle.speed('fastest')
turtle.setheading(0)
text(turtle, '%s' % (nome), 20, 'pink', txt_hor, txt_vert)
turtle.onclick(lambda x, y, n=nome, t=turtle: tnome_handler(n, t, x, y))
screen = Screen()
screen.setup(WIDTH, HEIGHT)
caca(dict_alunos, 'mm')
screen.mainloop()
我还重新编写了代码,以适应更常见的编程设计。