Home > Net >  trying to make tkinter output full string
trying to make tkinter output full string

Time:07-13

I am trying to make a simple tkinter character converter. I have this code:

from tkinter import *
import tkinter as tk
from numpy import binary_repr

window = Tk()
window.title("CHARACTER CONVERTER")
window.geometry('600x500')

frame = Frame(window)
input = Entry(frame,width = 50)
input.pack()
text = Text(window, width=40, height=40, wrap = "none", font = ('ariel',13),foreground='red', background='black')

def ASC():
    global result
    result = input.get()
    len(result)
    for char in result:
        ascii = ord(char)
        P = (char, "\t", ascii)    
    text.insert(tk.END, P)

button2 = Button(frame, text = 'ASCII',bg='black',fg='red', command = ASC)

button2.pack(side = LEFT)
frame.pack(side = TOP)
text.pack()
window.mainloop()

When I try using the button for the ASC callback, it only shows the information for the last letter of the string in the text field. How do I make it show information for the whole string?

CodePudding user response:

It is because you execute text.insert(tk.END, P) after the for loop, so it only inserts the result of P in last iteration of the for loop.

You need to put text.insert(tk.END, P) inside the for loop instead:

def ASC():
    global result
    result = input.get()
    len(result)
    for char in result:
        ascii = ord(char)
        P = f'{char}\t{ascii}\n'
        text.insert(tk.END, P)

CodePudding user response:

Would it better if we used Python 3.8 by using Walrus?

def ASC():   
    len(result := input.get())
    for char in result:
        ascii = ord(char)
        P = f'{char}\t{ascii}\n'
        text.insert(tk.END, P)

That would be helpful.

  • Related