Skip to content
Advertisement

How can I modify a label in tkinter?

I have been trying to figure out a way to modify the label to print element 1 to 4 in a line and repeat. I have attached a picture to hopefully clarify what I am trying to accomplish.

My goal is to make the results look like the following

1 A 2 B 3 C 4 D

1 a 2 b 3 c 4 d

enter image description here

my_entries = []

#prints the result
def something():
   entry_list =''
   index = 0
   for entries in my_entries:
      index+=1
      print(entries.get() + ' ' +str(index))
      entry_list = entry_list + str(index) + ' ' + str(entries.get()) + 'n'
      if index == 4:
         index = 0
      my_label.config(text=entry_list)
   
   #prints the element
   print('n'+my_entries[1].get())


def get_value():
    my_entries.clear()
    value = vialEntry.get()
    try:
        #print(int(value))
        return int(value)
    except ValueError:
        return None

#this function will create the inputs for the vials elements 
def make_entry():  
   num = get_value()
   print(num)
   tk.Label(master, text = "Name ").grid(row=1, column=1)
   tk.Label(master, text = "Time ").grid(row=1, column=2)
   tk.Label(master, text = "Temp ").grid(row=1, column=3)
   tk.Label(master, text = "Freq ").grid(row=1, column=4)
   #row loop
   for y in range(num):
      #column loop
      for x in range(4):
         user_entery = Entry(master)
         tk.Label(master, text = "Element: "+str(y+1)).grid(row=y+2, column=0, pady=5)
         user_entery.grid(row=y+2, column=x+1, pady=0, padx=5)
         my_entries.append(user_entery)

#end of make_entry function

my_button = Button(master, text="Click me", command=something)
my_button.grid(row=23, column=0, pady=20)
tk.Label(master, text = "Results: ").grid(row=24, column=0)
my_label = Label(master, text='')
my_label.grid(row=25, column=0, pady=0)

Advertisement

Answer

You added n after each index/value pair. You need to add n after 4 index/value pairs instead:

def something():
   entry_list =''
   index = 0
   for entries in my_entries:
      index+=1
      print(entries.get() + ' ' + str(index))
      entry_list += str(index) + ' ' + str(entries.get())
      if index == 4:
         index = 0
         entry_list += 'n'
      else:
         entry_list += ' '

   my_label.config(text=entry_list)

   #prints the element
   print('n'+my_entries[1].get())

Note that the for loop can be simplified as below:

def something_():
    entry_list = ''
    for i, entry in enumerate(my_entries):
        entry_list += f'{i%4+1} {entry.get()}' + ('n' if i%4 == 3 else ' ')
    # or one-liner
    #entry_list = ''.join(f'{i%4+1} {entry.get()}' + ('n' if i%4 == 3 else ' ') for i,entry in enumerate(my_entries))
    my_label.config(text=entry_list)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement