tkinter:使用for循环将对象移动到随机位置

时间:2019-01-06 17:45:08

标签: python for-loop tkinter

我使用python tkinter,并且尝试使用for循环将方舟/太阳(仅1次注入)移动到(0,500)到(800,500)之间的随机位置,因此每次运行时它将位于一个新位置我一直没有这样做。如果有人可以帮助我,那将意味着很多。

            from tkinter import *
            from random import *
            myInterface = Tk()
            screen = Canvas( myInterface, width=800, height=800, background="white" )
            screen.pack()

            #sky

            ##Sky
            y = 0
            y2 = 22
            skyOptions = ["#4C1D6D","#53236E","#5A2970","#623072","#693674","#703D75",\
                          "#784377","#7F4979","#86507B","#8E567C","#955D7E","#9C6380",\
                          "#A46A82","#AB7083","#B27685","#BA7D87","#C18389","#C88A8A",\
                          "#D0908C","#D7968E","#DE9D90","#E6A391", "#EDAA93","#F4B095"]
            for sky in range (1,24):
                skyColour = (skyOptions[sky%24]) 
                screen.create_rectangle (0,y,1000,y2, fill = skyColour, outline = skyColour)
                y = y + 22
                y2 = y2 + 22





            #sun (Make it randomly move plz)
            screen.create_arc(150, 250, 500, 800 ,start=0, extent=180, fill= "#fd8953", outline = "#fd8953")

            screen.update 



            spacing = 50 
            for x in range(0, 1000, spacing): 
                screen.create_line(x, 25, x, 1000, fill="red")
                screen.create_text(x, 5, text=str(x), font="Times 9", anchor = N)

            for y in range(0, 1000, spacing):
                screen.create_line(25, y, 1000, y, fill="blue")
                screen.create_text(5, y, text=str(y), font="Times 9", anchor = W)

            screen.update()

1 个答案:

答案 0 :(得分:0)

使用coords()函数在画布上移动小部件的简单示例:

from tkinter import *
from random import *

myInterface = Tk()
screen = Canvas( myInterface, width=800, height=800, background="white" )
screen.pack()

#sun (Make it randomly move plz)
arc = screen.create_arc(150, 250, 500, 800 , start=0, extent=180,
                        fill= "#fd8953", outline = "#fd8953")

def random_move(event):
    # Generate random numbers for x and y between 0 and 99
    x = randrange(0, 100)
    y = randrange(0, 100)
    # Move arc to original + random x, y position
    screen.coords(arc, [150+x, 250+y, 500+x, 800+y])

# Create binding so random_move() is easy to invoke.
myInterface.bind('<space>', random_move)

# start mainloop() which runs the application
myInterface.mainloop()

您需要启动应用程序主循环,否则程序将在创建窗口和小部件之后停止。 mainloop侦听事件(鼠标,键盘等)。

也:那是很多代码,其中大多数与您的问题无关。尝试最小化问题中的代码。

我将<space>绑定到random_move()函数,因此只需为每个动作都打上空格。

然后;查看The Tkinter Canvas Widget