首页 > 解决方案 > 在 tkinter 网格中上传图像

问题描述

试图将我的父窗口拆分为几个功能部分,其中一个将处理天气数据等,另一个将位于右侧并包含地图图像,最好以全高延伸。图像不想出现虽然..请帮助

import pyowm
from tkinter import *
import tkinter.messagebox
from PIL import Image, ImageTk

owm = pyowm.OWM('....')  # You MUST provide a valid API key
class MyWindow(tkinter.Frame):
    def __init__(self, win):
        super(MyWindow, self).__init__()
        self.lbl=Label(win, text="Weather info", fg='black', font=("Helvetica", 11))
        self.lbl1=Label(win, text='Wind speed')
        self.lbl2=Label(win, text='Wind direction')

        self.lbl.grid(row = 0, column = 0, sticky =  W, pady = 2) 
        self.lbl1.grid(row = 1, column = 0, sticky = W, pady = 2)
        self.lbl2.grid(row = 2, column = 0, sticky = W, pady = 2)

        # widgets for destination and weather output
        self.e1=Entry()
        self.e2=Entry()
        self.e3=Entry(bd=3)

        # this will arrange entry widgets 
        self.e1.grid(row = 0, column = 1, pady = 2) 
        self.e2.grid(row = 1, column = 1, pady = 2)
        self.e3.grid(row = 2, column = 1, pady = 2)

        self.btn1 = Button(win, text='Get weather', command=self.getWeather)
        self.btn1.grid(row = 3, column = 1, pady = 2)

        self.btn1.bind('<Button-1>', self.getWeather)

        img = Image.open(r"/User/.../pic.png")
        photo = ImageTk.PhotoImage(img) 

        # setting image with the help of label 
        self.imgLBL = Label(self, image = photo)
        self.imgLBL.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5)
        self.imgLBL.image = photo

    #### Get weather function, etc...###

window=Tk()
mywin=MyWindow(window)
window.title('name')
window.geometry("2732x2048")
window.configure(bg='grey')
window.mainloop()

标签: pythonimagetkintergridtkinter-layout

解决方案


用这个替换最后几行:

self.photo = ImageTk.PhotoImage(Image.open(r"/User/.../pic.png"))

# setting image with the help of label
self.imgLBL = Label(window, image=self.photo)
self.imgLBL.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5)
self.imgLBL.image = self.photo

推荐阅读