Reputation: 25
I am new to GUI programming. So please excuse me if this sounds trivial.
I am doing a project where I have to display images of sign language which correspond to the text I input.
For example, if I input "Hello", it should display images of Sign Language "H" then "E" then "L" and so on side by side.
The problem is in case I input a long text, the images go out of the window and I cannot even scroll horizontally.
I would like it to automatically put images in a new line after the entire width of the screen gets used up.
Here is my code:
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()
Here are some screenshots which might help:
Image where text is short - fits in the window
Image where text is long - few characters go out of the window
Upvotes: 0
Views: 151
Reputation: 29317
What you want is a responsive grid, and for this you can use the Tkinter's grid
manager.
Here is one way to do it by setting a maximum length and inserting images in the next row when that length is reached:
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()
Upvotes: 0
Reputation: 22493
You can use grid
instead of pack
to achieve what you want.
For example:
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
Upvotes: 1