Updating Label text tkinter

Viewed 30
from tkinter import *
import tkinter as tk

def text_to_binary(convert):
    for x in convert: # iterates over each character in the list
        ascii_values = ord(x) #gets the ascii value for x
        binary = format(ascii_values,'b')
        if len(binary) == 7:
            tk.Label(text="'0',binary")
            tk.Label.pack()
        elif len(binary) == 6:
            tk.Label(text="'00',binary")
            tk.Label.pack()
        else:
            tk.Label(text=binary)
            tk.Label.pack()

###MAINLINE###
window = tk.Tk()
window.title('Binary Converter')
window.geometry("450x120")

entry = tk.Entry(width=50)
entry.pack()

result = entry.get()

btn_convert = tk.Button(text='Convert it!', command=text_to_binary(result))
btn_convert.pack()

window.mainloop()

I'm not sure what I'm doing wrong. I want to use the function I created to convert bianry, it does that, but I don't know how to get that running with tkinter gui. Little help?

1 Answers

Below are the issues in your code:

  • both from tkinter import * and import tkinter as tk are executed. Wildcard import is not recommended, so remove from tkinter import *;
  • calling result = entry.get() right after entry is created, so result will be empty string;
  • command=text_to_binary(result) will execute text_to_binary(result) immediately without clicking the button. It should be command=lambda: text_to_binary(entry.get()) instead;
  • tk.Label.pack() will raise exception. .pack() should be called on instance of tk.Label();

Below is the modified code:

import tkinter as tk

def text_to_binary(convert):
    # clear existing result
    for w in result.winfo_children():
        w.destroy()

    for x in convert: # iterates over each character in the list
        ascii_values = ord(x) #gets the ascii value for x
        binary = format(ascii_values, '08b')
        tk.Label(result, text=binary).pack()

###MAINLINE###
window = tk.Tk()
window.title('Binary Converter')
#window.geometry("450x120")

entry = tk.Entry(window, width=50)
entry.pack()

btn_convert = tk.Button(window, text='Convert it!', command=lambda: text_to_binary(entry.get()))
btn_convert.pack()

# frame for the conversion result
result = tk.Frame(window)
result.pack()

window.mainloop()
Related