简体   繁体   中英

Problems with Tkinter

Writing a little programm on Python 3. There is a rectangle and it has to bounce from walls(borders of a window)

check=False

from tkinter import*
rect_x=50#x0 of rect
rect_y=50#y0 of rect
rect_x1=rect_x+rect_x#x1 of rect
rect_y1=rect_y+rect_y#y1 of rect
rect_change_x=5#change X speed
rect_change_y=3#change Y speed
root=Tk()

while check==False:

    if rect_y > 450 or rect_y < 0:
        rect_change_y = rect_change_y * -1
    if rect_x > 650 or rect_x < 0:
        rect_change_x = rect_change_x * -1


    rect_x+=rect_change_x#changing x
    rect_y+=rect_change_y#changing y
    rect_x1+=rect_change_x#changing x1
    rect_y1+=rect_change_y#changing y1



    c=Canvas(root,bg='yellow',width=700,height=500)
    c.pack()
    rect=c.create_rectangle(rect_x,rect_y,rect_x1,rect_y1,fill='black')



root.mainloop()

I guessed,that everything is Ok,but when I run this programm nothing happens.Tkinter window is not appearing. What's wrong with it,where i have a mistake?

To display something, you have to enter the eventloop

The last line

root.mainloop()

does that. Until you call this line, nothing is drawn.
You do everything in a loop.

Use async programming. Schedule the next paint with some timer.

check=False

from tkinter import*
rect_x=50#x0 of rect
rect_y=50#y0 of rect
rect_x1=rect_x+rect_x#x1 of rect
rect_y1=rect_y+rect_y#y1 of rect
rect_change_x=5#change X speed
rect_change_y=3#change Y speed
root=Tk()

def paintloop():
    global check,rect_x,rect_y,rect_x1,rect_y1,rect_change_x,rect_change_y
    root.after(100, paintloop)
    if rect_y > 450 or rect_y < 0:
        rect_change_y = rect_change_y * -1
    if rect_x > 650 or rect_x < 0:
        rect_change_x = rect_change_x * -1
     ...


root.after(0,paintloop)
root.mainloop()

Some other notes: don't create a new canvas every time. Currently you create N canvas with the first frame, the next one is the second, and display them all below the previous one.
After you finish the while loop (never).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM