如何在tkinter风中绘制图像

2024-09-28 21:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在tkinter窗口中绘制图像(我使用的是Python3.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

我很清楚间距有点乱,但这是在复制时发生的


Tags: selfifinittkinterdefrootclasselif
4条回答

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

如果你想用线条、圆圈等画一些东西,可以使用canvas小部件

您需要使用一个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版本,您只能读取GIFPGMPPM类型的图像-如果需要其他文件类型,请检查this answer

Canvas小部件非常强大,允许您定位图像,通过"canvas.update"调用显示图像上的内容,并通过"canvas.delete(item_id)"调用移除项显示程序。检查它的documentation

虽然Tkinter对于您的简单游戏来说已经足够了,但是考虑一下^{},以获得更好的多媒体支持,或者Pyglet,或者甚至更高级别的称为Kivy的多媒体框架。

*(更新):自2015年起,Pillow-a fork取代了旧的PIL项目,恢复了项目的正常开发,包括对Python3.x的支持

您需要使用一个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版本,您只能读取GIFPGMPPM类型的图像-如果需要其他文件类型,请检查this answer

Canvas小部件非常强大,允许您定位图像,通过"canvas.update"调用显示图像上的内容,并通过"canvas.delete(item_id)"调用移除项显示程序。检查它的documentation

虽然Tkinter对于您的简单游戏来说已经足够了,但是考虑一下^{},以获得更好的多媒体支持,或者Pyglet,或者甚至更高级别的多媒体框架Kivy

*(更新):自2015年起,Pillow-a fork取代了旧的PIL项目,恢复了项目的正常开发,包括对Python3.x的支持

相关问题 更多 >