Search code examples
pythontkinteremoji

How to display colored emojis in tkinter?


Is there any way to display colored emojis in tkinter?

Here's the code:

from tkinter import *
import pyperclip

root = Tk()

def copy():
    pyperclip.copy(button['text'])
    print("Copied!")

button = Button(root , text = "😄" , font = "arial 70" , command = copy)
button.pack()

mainloop()

When I run this code, I get something like this:

enter image description here

Here, the emoji shown in the button is completely black and it is not colored.

I know I could have used an image of the emoji in my button, but it won't be possible if I have to do the same thing for hundreds of emojis.

What I want is to make the emoji colored so that it will be easier for people to recognize it.

Is there any way to achieve this in tkinter?

It would be great if anyone could help me out.


Solution

  • pip install pywin32, 
    pip install pillow
    

    and

    from PIL import Image, ImageDraw, ImageFont, ImageTk
    import tkinter as tk
    import win32clipboard
    
    def emoji_img(size, text):
        font = ImageFont.truetype("seguiemj.ttf", size=int(round(size*72/96, 0))) 
        # pixels = points * 96 / 72 : 96 is windowsDPI
        im = Image.new("RGBA", (size, size), (255, 255, 255, 0))
        draw = ImageDraw.Draw(im)
        draw.text((size/2, size/2), text, embedded_color=True, font=font, anchor="mm")
        return ImageTk.PhotoImage(im)
    
    def copy():
        emoji_data = button['text']
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, emoji_data)
        win32clipboard.CloseClipboard()
        print("Copied!", emoji_data)
    
    root = tk.Tk()
    text="😄"
    emoji = emoji_img(80, text)
    button = tk.Button(root, image=emoji, text=text, command=copy)
    button.pack()
    root.mainloop()