想要做一个点击按钮,打开显示图片的窗口。在网上找了类似的功能,但是很难做到将图片居中,现在总结使用两种方法实现。
首先,准备窗口,设置相关参数,如窗口大小,窗口标题等。
窗口用 tkinter
实现。导入包 import tkinter as tk
。
W = 900
h = 600
root = tk.Tk()
root.geometry("{}x{}".format(w, h)) # 设置窗口大小
root.title('测点位置') # 设置窗口标题
准备要展示的图片路径,使用 ImageTk
进行导入图片。
from PIL import Image, ImageTk
strPng = './xxx.png'
photo = ImageTk.PhotoImage(file=strPng) # 其中 strPng 是图片路径
rootLabel = tk.Label(root, image=photo)
rootLabel.place(x=0, y=0)
root.mainloop()
通过 place
方式放置 label
很难放到窗口的居中位置,还需要去计算窗口大小和坐标的关系。所以改为用 grid
方式放置。再通过窗口的 .columnconfigure
和 .rowconfigure
就很容易实现。设置 weight = 1
可以让网格内容自动调整大小。
strPng = './xxx.png'
photo = ImageTk.PhotoImage(file=strPng)
rootLabel = tk.Label(root, image=photo)
rootLabel.grid(column=0, row=0)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.mainloop()
有时图片太大,会导致显示不全,所以在打开图片的时候,最好调整大小后在打开。
def resize(nX, nY):
xNew = w # 可以自己设置调整后的大小
yNew = int(nY * w / nX)
return (xNew, yNew)
photo = ImageTk.PhotoImage(file=strPng)
photoNew = Image.open(strPng).resize(resize(photo.width(), photo.height()))
photo = ImageTk.PhotoImage(photoNew)
def fireupPosition(self):
def resize(nX, nY):
xNew = 600
yNew = int(nY * 600 / nX)
return (xNew, yNew)
root = tk.Tk()
root.geometry("900x600")
root.title('测点位置')
strPng = './xxx.png'
photo = ImageTk.PhotoImage(file=strPng)
photoNew = Image.open(strPng).resize(resize(photo.width(), photo.height()))
photo = ImageTk.PhotoImage(photoNew)
rootLabel = tk.Label(root, image=photo)
rootLabel.grid(column=0, row=0)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.mainloop()
一开始找到的文章是使用 button 来实现的,也比较好做到居中,但是展示效果我觉得没有 label 好看。实现步骤和上面差不多。这里直接放完整代码。
使用 button 实现的话,可以使用 .pack(side=tk.BOTTOM)
来选择位置。 bottom 和 top 可以是居中,但是会偏下或者偏上。left 和 right 就是左右。不能使用 center ,会报错。
def fireupPosition(self):
def resize(nX, nY):
xNew = 600
yNew = int(nY * 600 / nX)
return (xNew, yNew)
root = tk.Tk()
root.geometry("900x600")
root.title('测点位置')
rootButton = tk.Button(root)
photo = tk.PhotoImage(file='./pqrcc/imgs/position.png')
rootButton.config(image=photo)
rootButton.pack(side=tk.BOTTOM)
root.mainloop()
https://www.pythonheidong.com/blog/article/300254/b5d423cb096b99073672/
https://blog.csdn.net/weixin_40751444/article/details/126418718