Python中的tkinter移动对象,就像在另一个def中创建的那样

时间:2016-10-15 19:07:56

标签: python python-3.x tkinter

我正在制作飞扬的鸟式游戏。我的问题是我无法移动已在另一个def上创建的管。 我的代码是

from tkinter import *
from random import randint
window = Tk()
c = Canvas(window, width=800, height=800, bg='steelblue')
tube11 = randint(600, 650)
tube12 = randint(400, 700)
def createtubes():
    tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green')
    tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green')   
def automovement():
    if True:
        c.move(tube1, -3.5, 0)
        c.move(tube2, -3.5, 0)
    window.update_idletasks()
    window.after(10, automovement)
window.after(60, createtubes)
window.after(10, automovement)
c.pack()
window.mainloop()

2 个答案:

答案 0 :(得分:1)

尝试创建一个类

from tkinter import *
from random import randint
window = Tk()
c = Canvas(window, width=800, height=800, bg='steelblue')
tube11 = randint(600, 650)
tube12 = randint(400, 700)
class Tubes:
    def __init__(self):
        self.createtubes()
    def createtubes(self):
        self.tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green')
        self.tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green')   
    def automovement(self):
        if True:
            c.move(self.tube1, -3.5, 0)
            c.move(self.tube2, -3.5, 0)
        window.update_idletasks()
        window.after(10, self.automovement)
tube = Tubes()
window.after(10, tube.automovement)
c.pack()
window.mainloop()

答案 1 :(得分:1)

您还可以在矩形上使用标签选项。

tube1 = c.create_rectangle(800, 800, tube11, tube12, fill='green', tags='tube')
tube2 = c.create_rectangle(800, 0, tube11, 200, fill='green', tags='tube')

在你的功能中只有一个动作:

c.move('tube', -3.5, 0)