循环中的Tkinter网格布局

时间:2016-07-23 21:04:41

标签: python-3.x tkinter

我在网格布局上苦苦挣扎 - 基本上我想在循环中打印一些数据,如下所示: enter image description here

但是我不能自己解决这个问题。我设法让它正常工作,但只是为了第一个条目 - 我的代码:

from tkinter import *
from PIL import Image, ImageTk
import urllib.request
import io

app = Tk()
images = []

for i in range(0, 8):
    text1 = Label(font=("Helvetica",10), text="top, left", cursor="hand2")
    text2 = Label(font=("Helvetica",10), text="top, right")
    text3 = Label(font=("Helvetica",10),text="lower")

    image = "https://www.gravatar.com/avatar/b9630126afbff209bb068195307a5e4c?s=328&d=identicon&r=PG"
    get_image = urllib.request.urlopen(image).read()
    im1 = Image.open(io.BytesIO(get_image))
    im_small = im1.resize((70, 70))
    im = ImageTk.PhotoImage(im_small)
    image1 = Label(app, image=im)
    images.append(im)

    image1.grid(rowspan=2, column=0, sticky=W)
    text1.grid(row=0, column=1, sticky=W)
    text2.grid(row=0, column=2, sticky=W)
    text3.grid(row=1, column=1, sticky=W)

app.mainloop()

结果:

enter image description here

我也试过这个:

from tkinter import *
from PIL import Image, ImageTk
import urllib.request
import io

app = Tk()
images = []

for i in range(0, 8):
    text1 = Label(font=("Helvetica",10), text="top, left", cursor="hand2")
    text2 = Label(font=("Helvetica",10), text="top, right")
    text3 = Label(font=("Helvetica",10),text="lower")

    image = "https://www.gravatar.com/avatar/b9630126afbff209bb068195307a5e4c?s=328&d=identicon&r=PG"
    get_image = urllib.request.urlopen(image).read()
    im1 = Image.open(io.BytesIO(get_image))
    im_small = im1.resize((70, 70))
    im = ImageTk.PhotoImage(im_small)
    image_cover = Label(app, image=im)
    images.append(im)

    image_cover.grid(rowspan=2, column=0, sticky=W)
    text1.grid(row=i+1, column=1, sticky=W)
    text2.grid(row=i+1,column=2)
    text3.grid(row=i+2, column=1, sticky=W)

app.mainloop()

由于图片应占据两行(让我们称之为1和2),"左上角"应该在第1列的第1行,"在右上角"在第2列,在第2行中较低。

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的东西:

from tkinter import *
root = Tk()
root.geometry("500x500")

imgvar = PhotoImage(file="world.gif")

for i in range(5):
    Label(root, image=imgvar, bg='red', bd=10, relief='groove').grid()
    Label(root, text="Upper", bg='blue', bd=5, relief='groove').grid(column=1, row=i, sticky=N)
    Label(root, text="Lower", bg='green', bd=5, relief='groove').grid(column=1, row=i, sticky=S)