tkinter设置背景图片
时间: 2023-07-22 08:39:24 浏览: 120
要在 Tkinter 中设置背景图片,可以使用以下步骤:
1. 导入 `tkinter` 和 `PIL` 库:
```python
from tkinter import *
from PIL import Image, ImageTk
```
2. 创建窗口并设置大小:
```python
root = Tk()
root.geometry("500x500")
```
3. 加载图片并将其放置在标签中:
```python
image = Image.open("image.jpg")
bg_image = ImageTk.PhotoImage(image)
bg_label = Label(root, image=bg_image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
```
4. 将其他部件放置在标签上方即可:
```python
button = Button(root, text="Click Me!")
button.place(x=250, y=250)
root.mainloop()
```
完整的示例代码如下:
```python
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.geometry("500x500")
image = Image.open("image.jpg")
bg_image = ImageTk.PhotoImage(image)
bg_label = Label(root, image=bg_image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
button = Button(root, text="Click Me!")
button.place(x=250, y=250)
root.mainloop()
```
阅读全文