如何在Python中改变颜色?

2024-09-29 06:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

from tkinter import *

def move():
    global x1, y1, dx, dy, flag, n

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360:
        n = 0
        x1, dx, dy = 360, 0, 15

    if y1 > 360:
        n = 1
        y1, dx, dy = 360, -15, 0

    if x1 < 10:
        x1, dx, dy = 10, 0, -15
        n = 2

    if y1 < 10:
        y1, dx, dy = 10, 15, 0
        n = 3

    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

def stop():
    global flag
    flag = 0

def start():
    global flag
    if flag == 0:
        flag = 1
        move()

###

x1, y1 = 10, 10
dx, dy = 15, 0
color = [["white"], ["red"], ["green"], ["blue"]]
n = 0

flag = 0

###

abl1 = Tk()
abl1.title("Animációs gyakorlat Tkinter-rel")

can1 = Canvas(abl1, bg = "dark grey", height = 400, width = 400)
can1.pack(side=LEFT)

oval1 = can1.create_oval(x1, y1, x1 + 30, y1 + 30, fill = color[n])

but1 = Button(abl1, text = "Quit", command = abl1.destroy).pack(side=BOTTOM)
but2 = Button(abl1, text = "Start", command = start).pack()
but3 = Button(abl1, text = "Stop", command = stop).pack()

abl1.mainloop()

当球到达正方形的边缘时,它必须改变颜色。现在有了这个颜色列表,如果有了ifs,它什么也做不了,我也不知道出了什么问题。我尝试了很多不同的变体,但也没用。 谢谢你的帮助。在


Tags: textmoveifdefbuttonglobalcommandpack
2条回答

在move函数中,每次迭代都必须设置itemconfig()fill参数。对can1.create_oval()的调用返回椭圆形的ID,可以将其作为第一个参数传递到itemconfig()方法中。然后可以按照下面的代码从那里设置填充。不过,这并不是编写代码的最有效方法。对于所有的全局变量,最好将此脚本放入一个类中。在

def move():
    global x1, y1, dx, dy, flag, n

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360:
        n = 1 
        x1, dx, dy = 360, 0, 15
        can1.itemconfig(1, fill=color[n])

    if y1 > 360:
        n = n + 2
        y1, dx, dy = 360, -15, 0
        can1.itemconfig(1, fill=color[n])

    if x1 < 10:
        n = 2
        x1, dx, dy = 10, 0, -15
        can1.itemconfig(1, fill=color[n])

    if y1 < 10:
        n = 3
        y1, dx, dy = 10, 15, 0
        can1.itemconfig(1, fill=color[n])

    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

在您的x1 > 360签入move()内,n == 1应该是{}。在

我假设n是您用作列表索引的变量。如果是这样,您需要在move()底部的flag > 0检查之前添加以下行:

can1.itemconfig(oval1, fill=color[n])

这应该会改变你想要的颜色。在

复制粘贴您的move()的我的版本:

^{pr2}$

编辑:Jaredp37的答案肯定比我的答案更有效,因为每次调用函数时,我的答案都会尝试改变颜色。在

相关问题 更多 >