如何在tkinter窗口中绘制图像

pip*_*117 8 python user-interface image tkinter draw

如何在tkinter窗口中绘制图像(我使用的是python 3.3)?我正在寻找一个声明,它会在tkinter窗口的给定位置绘制图像.

是啊...

任何答案将不胜感激.这里是我想要使用代码的程序的源代码(如果它可以被称为),以防你需要它.

from tkinter import *

class craftClass():
    def __init__(self, x = 80, y = 80, xmotion = 0, ymotion = 0, health = 20):
        self.xPos, self.yPos = x, y
        self.dx, self.dy = xmotion, ymotion
    def moveCraft(self):
        self.xPos += self.dx
        self.yPos += self.dy

class missileClass():
    def __init__(self, x = 0 , y = 0):
        self.xPos, self.yPos = x, y

class alienClass():
    def __init__(self, x, y):
        self.xPos, self.yPos = x, y

    def moveForCraft(self, craftX, craftY):
        if self.xPos < craftX:
            self.xPos += 2
        elif self.xPos > craftX:
            self.xPos -= 2
        else:
            pass

    if self.yPos < craftY:
        self.yPos += 2
    elif self.yPos > craftY:
        self.yPos -= 2
    else:
        pass

craft = craftClass()
missileArray = []
alienArray = []

def keypress(event):
    if event.keysym == 'Escape':
        root.destroy()
x = event.char
if x == "w":
    craft.dy = 1
elif x == "s":
    craft.dy = -1
elif x == "a":
    craft.dx = -1
elif x == "d":
    craft.dx = 1
else:
    print(x)

root = Tk()
print(craft.dx)
while True:
try:
    root.bind_all('<Key>', keypress)
    craft.moveCraft()
    root.update()
except TclError:
    print("exited. tcl error thrown. llop broken")
    break
Run Code Online (Sandbox Code Playgroud)

我很清楚间距是混乱的,但这是复制时发生的事情

jsb*_*eno 6

您需要使用Canvas小部件将图像放在指定的(x,y)位置.

在Python 3中,您可以这样做:

import tkinter

tk = tkinter.Tk()
can = tkinter.Canvas(tk)
can.pack()
img = tkinter.PhotoImg("<path/to/image_file>.gif")
can.create_image((x_coordinate, y_coordinate), img)
Run Code Online (Sandbox Code Playgroud)

请注意,由于Python 3没有官方PIL*版本,您只能阅读类型的图像GIF,PGM或者PPM- 如果您需要其他文件类型,请查看此答案.

Canvas小部件非常强大,允许您定位图像,通过"canvas.update"呼叫显示其中的内容,并通过调用删除项目显示器"canvas.delete(item_id)".检查其文档.

虽然Tkinter足以满足您的简单游戏需求,但请考虑一下Pygame,以获得更好的多媒体支持,或者可能是Pyglet,甚至是更高级别的多媒体框架Kivy.

*(更新):截至2015年,有一个Pillow - 一个代替旧PIL项目的分支,它恢复了项目的正确开发,包括对Python 3.x的支持