Home > Software design >  Tkinter: How to swich label text using buttons
Tkinter: How to swich label text using buttons

Time:11-08

import Tkinter
from Tkinter import ttk

root = tk()
root.mainloop()
label = ttk.Label(root, text = "This text I want to change")
label.grid()

def select_label_text():
    top = Toplevel()
    top.title("Select Name")

    def change_name(name):
        label.cofigure(text=name)
        top.destroy()

    label_names = [a,b,c...] #this has undefined strings
    for i in range(len(label_names)): #here I made a button for each different name
        ttk.button(top, text = label_names[i], command = lambda: change_name(label_names[i])).grid()

I want to change the label text to the button´s name when I press it. there are undefined buttons so I can't save each one to a variable.

ttk.Button(root, comand = select_label_text()).grid()

CodePudding user response:

You have many errors. Here is a version of your code, for Python 3, not Python 2, that at least runs. It may not do exactly what you want it to do, but it works, and it's a better starting point than what you posted. The modified code is as follows:

import tkinter # Tkinter
from tkinter import ttk

def select_label_text():
    top = tkinter.Toplevel()
    top.title("Select Name")

    def change_name(name):
        label.configure(text=name)
        top.destroy()


    label_names = ["a", "b", "c..."] #this has undefined strings
    for i in range(len(label_names)): #here I made a button for each different name
        ttk.Button(top, text=label_names[i], command=lambda i=i: change_name(label_names[i])).grid()

root = tkinter.Tk()
label = ttk.Label(root, text = "This text I want to change")
label.grid()
ttk.Button(root, command=select_label_text).grid()
root.mainloop()

You should do a diff comparison between your code and this version to see the changes.

  • Related