最近用到了tkinter,想用自己喜欢的图片作为背景,看了不少博客,可能是我少敲了什么,很少有能成功运行的,最后终于发现了一个可行方案,于是在这里记录一下(代码为原创) 图片使用的p站喜爱画师的作品(因为是以前保存的,抱歉没找到画师链接),侵删。

import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()
#背景
canvas = tk.Canvas(root, width=1200,height=699,bd=0, highlightthickness=0)
imgpath = 'background.gif'
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)

canvas.create_image(700, 500, image=photo)
canvas.pack()
entry=tk.Entry(root,insertbackground='blue', highlightthickness =2)
entry.pack()

canvas.create_window(100, 50, width=100, height=20,
                                       window=entry)



root.mainloop()

输出效果为

 下面来进行解释

使用canvas,其中width,height参数为画布的宽和高,bd(borderwidth)为 文本框边框宽度

canvas = tk.Canvas(root, width=1200,height=699,bd=0, highlightthickness=0)

使用PhotoImage,要注意,此处只能使用gif格式的图片,关于gif图片可以用ps打开jpg,png然后另存为gif即可获得gif格式的图片

imgpath = 'background.gif'
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)

此处的700,500为偏移参数,大家可以根据自己的需要进行调整

canvas.create_image(700, 500, image=photo)
canvas.pack()

此处将输入框作为canvas的window即可实现在canvas上出现输入框,按钮同理,将create_window()中window参数改为相应的button即可

entry=tk.Entry(root,insertbackground='blue', highlightthickness =2)
entry.pack()

canvas.create_window(100, 50, width=100, height=20,
                                       window=entry)

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐