简体   繁体   中英

Python - TKinter - Editing Widgets

I need a widget in TKinter to be a global widget, however, I need the text displayed in it to be different every time. I'm quite new with TKinter and haven't yet successfully managed to edit an option in a widget.

I assume it's something to do with widget.add_option() but the documentation is quite confusing to me and I can't figure out the command.

I specifically just need to edit the text = "" section.

Thanks

EDIT:

gm1_b_current_choice_label = Label(frame_gm1_b, text = "Current input is:\t %s"% str(save_game[6]))

I specifically need to update the save_game[6] (which is a list) in the widget creation, but I assume once the widget is created that's it. I could create the widget every time before I place it but this causes issues with destroying it later.

You can use the .config method to change options on a Tkinter widget.

To demonstrate, consider this simple script:

from Tkinter import Tk, Button, Label

root = Tk()

label = Label(text="This is some text")
label.grid()

def click():
    label.config(text="This is different text")

Button(text="Change text", command=click).grid()

root.mainloop()

When the button is clicked, the label's text is changed.

Note that you could also do this:

label["text"] = "This is different text"

or this:

label.configure(text="This is different text")

All three solutions ultimately do the same thing, so you can pick whichever you like.

You can always use the .configure(text = "new text") method, as iCodez suggested.

Alternatively, try using a StringVar as the text_variable parameter :

my_text_var = StringVar(frame_gm1_b)
my_text_var.set("Current input is:\t %s"% str(save_game[6]))
gm1_b_current_choice_label = Label(frame_gm1_b, textvariable = my_text_var)

Then, you can change the text by directly altering my_text_var :

my_text_var.set("Some new text")

This can be linked to a button or another event-based widget, or however else you want to change the text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM