Tkinter如何包装连续的图像系列

时间:2019-02-09 12:23:31

标签: python python-3.x tkinter

我是GUI编程的新手。所以,请问这听起来没什么。

我正在做一个项目,我必须显示与我输入的文字相对应的手语图像。

例如,如果我输入“ Hello”,它应该并排显示手语“ H”,“ E”,“ L”等图像。

问题是如果我输入了长文本,图像从窗口中移出,甚至无法水平滚动。

我希望在屏幕的整个宽度用完后自动将图像放在新行中。

这是我的代码:

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

aimg = ImageTk.PhotoImage(Image.open("path"))
bimg = ImageTk.PhotoImage(Image.open("path"))
# Similarly, I have cimg, dimg, and so on...

def a():
    apanel = Label(root, image=aimg)
    apanel.pack(side="left", fill="both", expand="yes")

def b():
    bpanel = Label(root, image=bimg)
    bpanel.pack(side="left", fill="both", expand="yes")
# Similarly, I have functions for all the characters

s = list(input("Enter text here").lower())
for i in s:
    if i == 'a':
        a()
    elif i == 'b':
        b()
    # So on

root.mainloop()

以下一些屏幕截图可能会有所帮助:

Image where text is short - fits in the window

Image where text is long - few characters go out of the window

2 个答案:

答案 0 :(得分:1)

您可以使用grid代替pack来实现所需的目标。

例如:

r,c = 0,0
def a():
    global r,c
    if c==5:
          r+=1
          c=0
    apanel = Label(root, image=aimg)
    apanel.grid(row=r,column=c)
    c+=1

答案 1 :(得分:0)

您想要的是一个响应式网格,为此,您可以使用Tkinter的grid管理器。

这是一种方法,可以设置最大长度,并在达到该长度时在下一行插入图像:

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

aimg = ImageTk.PhotoImage(Image.open("a.jpg").resize((20, 20)))
bimg = ImageTk.PhotoImage(Image.open("b.jpg").resize((20, 20)))

def a():
    apanel = Label(root, image=aimg)
    apanel.grid(row=r, column=c)

def b():
    bpanel = Label(root, image=bimg)
    bpanel.grid(row=r, column=c)

# Similarly, I have functions for all the characters

s = list(input("Enter text here: ").lower())

r = 0
c = 0
maxc = 10 # max nr. of columns
for i in s:
    if i == 'a':
        a()
    elif i == 'b':
        b()
    c+=1
    if (c==maxc): # when you reach the last column, go to the next row
        c = 0
        r += 1
    # So on


root.mainloop()