pythontkinterextended-ascii

Extended ASCII in tkinter


I'm trying to create an inspiration app, which displays random words. it works for alpha characters, but when a word has characters like öäü or ß in them, it just displays random gibberish.

Wanted Text: Rindfleischverpackungsetikettierungsgerät

Text displayed: Rindfleischverpackungsetikettierungsgerßt

Another Example:

screenshot showing characters

Here is my code for it (still very basic and functional)

import tkinter as tk
from random import randint

class ButtonBlock(object):
    def __init__(self, master):
        self.master = master
        self.button = []
        self.button_val = tk.IntVar()
        entry = tk.Entry()
        entry.grid(row=0, column=0)
        entry.bind('<Return>', self.onEnter)
    def onEnter(self, event):
        entry = event.widget
        num = int(entry.get())
        for button in self.button:
            button.destroy()
        for i in range(1, num+1):
            leine = randint(1, 1908815)
            print(leinen[leine])
            self.button.append(tk.Label(
                self.master, text=leinen[leine]))
            self.button[-1].grid(sticky='WENS', row=i, column=2, padx=1, pady=1)
    def onSelect(self):
        print(self.button_val.get())


if __name__ == '__main__':

    deutsch = open("WORT.txt", "r")
    leinen = deutsch.readlines()

    root = tk.Tk()
    ButtonBlock(root)
    root.mainloop()

Is there any way to allow tkinter to render the characters öäüß properly? (BTW WORT.txt is just a word list)


Solution

  • To read the extended ASCII characters in the text file, specify the encoding when you open the file like this:

    deutsch = open("WORT.txt", "r", encoding="latin1")
    

    This needs to be done because if encoding is not specified the default used is platform dependent (and apparently not the "latin1" needed on your system). See the documentation for the built-in open() function.