简体   繁体   中英

How to convert string into variable name in Python (tkinter)

Ok this is what I am trying to do.

import tkinter

def abc(buttonNumber):
    buttonNumber["text"] = rating[i]

b11 = tkinter.Button(top, text = "Name", command = abc("b11"))

Here, I want abc funciton to get called when someone click b11 button.

But I cannot use abc(b11) because, b11 is not defined yet.

So, If i use abc("b11") instead, I get this error:

TypeError: 'str' object does not support item assignment

Do I need to convert string into variable? If yes how?

Or It can be done in a better way?

Exemple using dictionary to variable name

dict = {}
x = "fizz" // variable name fizz
dict[x] = 4 // variable value

"Use {} curly brackets to construct the dictionary, and [] square brackets to index it. Separate the key and value with colons : and with commas , between each pair. Keys must be quoted As with lists we can print out the dictionary by printing the reference to it. A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. Dictionaries are mutable, which means they can be changed. The values that the keys point to can be any Python value. Dictionaries are unordered, so the order that the keys are added doesn't necessarily reflect what order they may be reported back.", font

your exemple:

x = "b11 "
dict[x] = null // value of the button (pointer), set value in the future
b11 = tkinter.Button(top, text = "Name", command = abc(dict["b11"]))

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