Reputation: 35
Let's take this as a sample program:
from tkinter import *
import random
win = Tk()
win.geometry('200x200')
alphabets = ["A", "B", "C"]
rand_alpha = random.choice(alphabets)
lbl = Label(win, font = 'Ariel 30',text = rand_alpha)
lbl.pack()
win.mainloop()
In this above program I wanted to change the texts of "rand_alpha" into an image file so that I could use PIL to modify it. Is it possible with python !?
Upvotes: 2
Views: 1302
Reputation: 47183
You can use ImageDraw
to create the image you want:
from tkinter import *
import random
from PIL import Image, ImageTk, ImageDraw, ImageFont
win = Tk()
win.geometry('200x200')
alphabets = ["A", "B", "C"]
rand_alpha = random.choice(alphabets)
image = Image.new('RGB', (200, 200), (255, 255, 255)) # adjust the size to what you want
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('arial.ttf', size=128) # adjust the font and size to what you want
w, h = draw.textsize(rand_alpha, font=font)
draw.text(((200-w)//2, (200-h)//2), font=font, text=rand_alpha, fill='black')
tkimage = ImageTk.PhotoImage(image)
lbl = Label(win, image=tkimage)
lbl.pack()
win.mainloop()
Refer to ImageDraw document for how to use it.
Upvotes: 2
Reputation: 5339
I have written an example with tkinter
and PIL
modules. I have added several comment to my code for the better understanding.
Code:
from tkinter import *
from PIL import Image, ImageDraw, ImageTk
import random
win = Tk()
win.geometry("200x200")
alphabets = ["A", "B", "C"]
rand_alpha = random.choice(alphabets)
img = Image.new("RGB", (100, 100), color="white") # Create a new 100x100 white image
d = ImageDraw.Draw(img) # Create Draw instance
d.text((50, 50), rand_alpha, fill=(255, 0, 0)) # Render the text to the image at 50x50 position with red color.
render = ImageTk.PhotoImage(img) # Rendering picture to TK
img = Label(win, image=render) # Insert picture to Label widget.
img.image = render
img.place(x=0, y=0) # Place the picture to the left-top corner
win.mainloop()
GUI:
Upvotes: 1
Reputation: 1159
Sure you could:
from tkinter import *
import random
from PIL import Image, ImageTk
img = ImageTk.PhotoImage(Image.open("Yourimage"))
win = Tk()
win.geometry('200x200')
alphabets = ["A", "B", "C"]
rand_alpha = random.choice(alphabets)
lbl = Label(win, font='Ariel 30', text=rand_alpha, image=img)
lbl.pack()
win.mainloop()
If you don't want to your image cover your text, you need to use compound=[CENTER,BOTTOM,TOP,LEFT,RIGHT]
.
Upvotes: 0