如何在tkinter窗口中绘制图像

时间:2012-09-03 14:51:47

标签: python image user-interface 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

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

4 个答案:

答案 0 :(得分: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)

请注意,由于Python 3没有正式的PIL * 版本,因此您只能阅读GIFPGM或{PPM类型的图片{1}} - 如果您需要其他文件类型,请检查this answer

“画布”窗口小部件非常强大,可让您定位图片,通过"canvas.update"调用显示图片上显示的内容,并通过"canvas.delete(item_id)"调用移除项目显示器。检查其documentation

虽然Tkinter足够适合您的简单游戏,但请考虑查看Pygame,以获得更好的多媒体支持,或者Pyglet,甚至更高级别的多媒体框架Kivy

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

答案 1 :(得分:2)

如果你想用线条,圆圈等画一些东西,那么画布小部件是可以使用的东西。

答案 2 :(得分:1)

这在很大程度上取决于文件格式。 Tkinter有一个PhotoImage类,如果您的图片是Labels,则可以很容易地在.gif中使用。您还可以轻松地将它们添加到画布小部件。否则,您可能希望使用PIL将图像转换为PhotoImage

答案 3 :(得分:1)

该示例在画布上显示图像。

from PIL import Image, ImageTk
  

从PIL(Python图像库)模块中,导入图像并   ImageTk模块。

self.img = Image.open("tatras.jpg") //your image name :)
self.tatras = ImageTk.PhotoImage(self.img)
  

Tkinter内部不支持JPG图像。作为解决方法,我们   使用Image和ImageTk模块。

canvas = Canvas(self, width=self.img.size[0]+20,
    height=self.img.size[1]+20)

我们创建了Canvas小部件。它考虑了图像的大小。比实际图像尺寸宽20px,高20px。

canvas.create_image(10, 10, anchor=NW, image=self.tatras)

参考,请参阅:https://tutorialspoint.com/python/tk_canvas.htm

相关问题