首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tkinter -弹跳图标脚本

Tkinter -弹跳图标脚本
EN

Stack Overflow用户
提问于 2018-07-16 04:35:26
回答 0查看 61关注 0票数 1

我正在写一个简单的弹跳图标程序(Python3.7,Windows10 x64)来体验一下Tkinter和canvases。我已经在下面发布了我的代码。我对这个程序的问题是它会剪切图标的边缘(在运动方向上)。如果我稍微放慢运动(通过增加after方法中的值),它不再剪切,但运动是断断续续的。也许我想得太多了,它基本上实现了我的目标。但是,如果这是一个重要的游戏或其他项目,如何防止这种情况?

代码语言:javascript
复制
from tkinter import *
import os
from PIL import Image, ImageTk

xinc, yinc = 5, 5

def load_image(width, height, imgpath):
    loadimg = Image.open(imgpath)
    pwid, phi = loadimg.size
    pf1, pf2 = 1.0*width/pwid, 1.0*height/phi
    pfactor = min([pf1, pf2])
    pwidth, pheight = int(pwid*pfactor), int(phi*pfactor)
    loaded = loadimg.resize((pwidth, pheight), Image.ANTIALIAS)
    loaded = ImageTk.PhotoImage(loaded)
    return loaded

def bounce():
    global xinc
    global yinc
    cwid = int(dash.cget('width'))
    chi = int(dash.cget('height'))
    x = dash.coords(dashposition)[0]
    y = dash.coords(dashposition)[1]
    if x > cwid-10 or x < 10:
        xinc = -xinc
    if y > chi-10 or y < 10:
        yinc = -yinc
    dash.move(dashposition, xinc, yinc)
    dash.after(15, bounce)

root = Tk()
root.configure(bg='black')

dash = Canvas(root, bg='black', highlightthickness=0, width=400, height=300)
dash.grid(row=0, column=0, padx=2, pady=2)

imagepath = os.getcwd() + '/img/cloudy.png'
image = load_image(20, 20, imagepath)

x, y = 10, 10
dashposition = dash.create_image(x, y, anchor=CENTER, image=image, tags=('current'))

bounce()

root.mainloop()

cloudy.png

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51352047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档