import tkinter as tk import random root = tk.Tk() root.geometry("200x100") root.title("求签") def get_fortune(): fortunes = ["大吉", "中吉", "小吉", "吉", "末吉", "凶", "大凶"] fortune = random.choice(fortunes) result.config(text="{},{}".format( "您的今日运势为", fortune)) button = tk.Button(root, text="求签", command=get_fortune) button.pack() result = tk.Label(root, text="") result.pack() root.mainloop()给该程旭添加一张背景图
时间: 2023-07-06 11:14:15 浏览: 161
要给这个程序添加一个背景图,你需要使用Tkinter的Canvas和PIL库。下面是修改后的代码:
```
import tkinter as tk
from PIL import Image, ImageTk
import random
root = tk.Tk()
root.geometry("200x100")
root.title("求签")
# 加载背景图片
bg_image = Image.open("background.jpg")
bg_photo = ImageTk.PhotoImage(bg_image)
bg_label = tk.Label(root, image=bg_photo)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
def get_fortune():
fortunes = ["大吉", "中吉", "小吉", "吉", "末吉", "凶", "大凶"]
fortune = random.choice(fortunes)
result.config(text="{},{}".format("您的今日运势为", fortune))
button = tk.Button(root, text="求签", command=get_fortune)
button.pack()
result = tk.Label(root, text="")
result.pack()
root.mainloop()
```
在这个代码中,我们首先导入了PIL库,用于处理图片。然后,我们使用PIL库加载了一张背景图片,并将其放置在一个标签中。注意,我们使用了place方法,将标签放置在(0,0)的位置,并设置其相对宽度和高度为1,这样标签就会占据整个窗口。
最后,我们将按钮和标签添加到窗口中,运行主循环,程序就可以正常运行了。
阅读全文
相关推荐

















