使用 tkinter 绘制星星

问题描述 投票:0回答:0

我正在尝试设置背景图像并使用此代码在其上方绘制星星

import tkinter as tk

# Create a new Tkinter window
root = tk.Tk()

# Load the background image
background_image = tk.PhotoImage(file="C:\\Users\\Stefa\\Downloads\\galaxy.jpeg")

# Create a new canvas
canvas = tk.Canvas(root, width=background_image.width(), height=background_image.height())
canvas.pack()

# Add the background image to the canvas
canvas.create_image(0, 0, anchor='nw', image=background_image)

# Define the coordinates for the vertices of the star
points=[200,20,80,396,380,156,20,156,320,396]

# Draw a polygon connecting the vertices to create the star
star_image = tk.PhotoImage(width=200, height=200)
star_canvas = tk.Canvas(star_image, width=200, height=200)
star_canvas.create_polygon(points, outline='blue', fill='blue')
canvas.create_image(0, 0, anchor='nw', image=star_image)

# Start the Tkinter event loop
root.mainloop()


我发现了很多错误。 有人也可以运行此代码并告诉我是否遇到与我相同的问题吗? 或者如果你也能找到我的任何解决方案(我已经尝试了 2 个多星期的代码和很多关于如何在 tkinter 中设置背景图像的代码,但没有任何帮助)

但是当我执行它时,它指出:

raceback (most recent call last):
  File "c:\Users\Stefa\Videos\Python exam\stef.py", line 7, in <module>
    background_image = tk.PhotoImage(file="C:\\Users\\Stefa\\Downloads\\galaxy.jpeg")
  File "C:\Users\Stefa\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\Stefa\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4038, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:\Users\Stefa\Downloads\galaxy.jpeg"
PS C:\Users\Stefa\Videos\Python exam>

有人可以帮助我吗?

python windows tkinter background-image project
© www.soinside.com 2019 - 2024. All rights reserved.