如何给这段代码添加背景图片import tkinter as tk import numpy as np def change_label(): button.destroy() label.config(text="请输入您的身高体重以及目标体重:") height_label.place(relx=0.5, rely=0.4, anchor="center") height_entry.place(relx=0.5, rely=0.45, anchor="center") weight_label.place(relx=0.5, rely=0.5, anchor="center") weight_entry.place(relx=0.5, rely=0.55, anchor="center") target_label.place(relx=0.5, rely=0.6, anchor="center") target_entry.place(relx=0.5, rely=0.65, anchor="center") submit_button.place(relx=0.5, rely=0.8, anchor="center")
时间: 2024-02-19 14:59:25 浏览: 66
可以使用 tkinter 的 Canvas 组件来添加背景图片。首先需要在 tkinter 中导入 Image 类,然后将图片打开并保存到一个变量中,最后将图片绘制到 Canvas 组件上即可。以下是修改后的代码:
```
import tkinter as tk
from PIL import Image, ImageTk
import numpy as np
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=600)
canvas.pack()
# 打开并保存图片
image = Image.open("background.png")
bg_image = ImageTk.PhotoImage(image)
# 在 Canvas 上绘制图片
canvas.create_image(0, 0, anchor=tk.NW, image=bg_image)
def change_label():
button.destroy()
label.config(text="请输入您的身高体重以及目标体重:")
height_label.place(relx=0.5, rely=0.4, anchor="center")
height_entry.place(relx=0.5, rely=0.45, anchor="center")
weight_label.place(relx=0.5, rely=0.5, anchor="center")
weight_entry.place(relx=0.5, rely=0.55, anchor="center")
target_label.place(relx=0.5, rely=0.6, anchor="center")
target_entry.place(relx=0.5, rely=0.65, anchor="center")
submit_button.place(relx=0.5, rely=0.8, anchor="center")
button = tk.Button(root, text="开始计算", command=change_label)
button.place(relx=0.5, rely=0.3, anchor="center")
label = tk.Label(root, text="欢迎使用BMI计算器!", font=("Arial", 20))
label.place(relx=0.5, rely=0.2, anchor="center")
height_label = tk.Label(root, text="身高(米):", font=("Arial", 16))
height_entry = tk.Entry(root, font=("Arial", 16))
weight_label = tk.Label(root, text="体重(千克):", font=("Arial", 16))
weight_entry = tk.Entry(root, font=("Arial", 16))
target_label = tk.Label(root, text="目标体重(千克):", font=("Arial", 16))
target_entry = tk.Entry(root, font=("Arial", 16))
submit_button = tk.Button(root, text="提交", font=("Arial", 16))
root.mainloop()
```
其中,`background.png` 是用于作为背景图片的图片文件,需要放在同一目录下。
阅读全文