首页 > 解决方案 > 在 tkinter 中使用 .place() 显示完整图像的问题

问题描述

我的代码看起来像这样,我不得不说我正在尝试创建的程序将有几个选项卡(8-10)和其中的许多小部件,所以我选择使用 .place() 设计图形界面. 我一直在尝试显示图片,但没有显示完整,我尝试使用画布和标签,但都显示了部分图片。

这是我的代码

from tkinter import * #GUI
from tkinter import ttk #GUI
from PIL import ImageTk,Image  
root = Tk()

root.title("Example") #Title

####get resolution
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#### end get resolution
frame = Frame(root)
frame.pack(fill="both",expand=1) 


frame.config(width=screen_width,height=screen_height)

tabControl = ttk.Notebook(root)

tab1 = ttk.Frame(tabControl) 
tabControl.add(tab1, text='Tab 1')
tab2 = ttk.Frame(tabControl) 
tabControl.add(tab2, text='Tab 2')

tabControl.place(x=0,y=round(screen_height * .2), 
width=round(screen_width),height=round(screen_height * .9))

frame_one = LabelFrame(tab1, text="Image")
frame_one.place(x=round(screen_width * .6),y=round(screen_height * 
.01),width=round(screen_width * .3),height=round(screen_height * .3))

frame_two = LabelFrame(tab1, text="Image")
frame_two.place(x=round(screen_width * .6),y=round(screen_height * 
.35),width=round(screen_width * .3),height=round(screen_height * .3))

frame_three = LabelFrame(tab1, text="Labels, radios, checkbuttons, 
buttons")
frame_three.place(x=round(screen_width * .01),y=round(screen_height * 
.01),width=round(screen_width * .55),height=round(screen_height * 
.65))

button = Button(tab1,text="Button")
button.place(x=round(screen_width * 0.45), y=round(screen_height * 
.66))

canv = Canvas(tab1)
img = ImageTk.PhotoImage(Image.open("test.jpg"))  # PIL solution
canv.create_image(0, 0, image=img, anchor=NW)
canv.place(x=round(screen_width * .605),y=round(screen_height * 0.03), 
width=round(screen_width * .29), height=round(screen_height * .28))

canv2 = Canvas(tab1)
img2 = ImageTk.PhotoImage(Image.open("test.jpg"))  # PIL solution
canv2.create_image(0, 0, image=img2, anchor=NW)
canv2.place(x=round(screen_width * .605),y=round(screen_height * 
0.37), width=round(screen_width * .29), height=round(screen_height * 
.28))

root.mainloop() 

我希望有人能帮我把图片完整地展示出来

标签: python-3.ximagetkinterlabel

解决方案


由于您使用 限制了画布place(...)的大小,因此画布的大小可能不足以显示完整图像。

您可以使用以下命令调整加载图像的大小以适合画布PIL.Image.thumbnail()

canv = Canvas(frame_one) # put into LabelFrame
canv.pack(fill='both', expand=1)
canv.update() # required to get the real size of canvas
w, h = canv.winfo_width(), canv.winfo_height()
img = Image.open("test.jpg")
img.thumbnail((w, h))
img = ImageTk.PhotoImage(img)
canv.create_image(w//2, h//2, image=img, anchor=CENTER)

canv2 = Canvas(frame_two)
canv2.pack(fill='both', expand=1)
canv2.update()
w, h = canv2.winfo_width(), canv.winfo_height()
img2 = Image.open("test.jpg")
img2.thumbnail((w, h))
img2 = ImageTk.PhotoImage(img2)
canv2.create_image(w//2, h//2, image=img2, anchor=CENTER)

请注意,thumbnail()仅当图像大小大于函数的给定大小时才会调整图像大小。


推荐阅读