简体   繁体   English

如何在Python中将字符串转换为变量名(tkinter)

[英]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. 在这里,我希望有人单击b11按钮时调用abc函数。

But I cannot use abc(b11) because, b11 is not defined yet. 但是我不能使用abc(b11)因为b11尚未定义。

So, If i use abc("b11") instead, I get this error: 因此,如果我改用abc("b11")abc("b11")收到此错误:

TypeError: 'str' object does not support item assignment TypeError:'str'对象不支持项目分配

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 “使用{}大括号来构建字典,并使用[]方括号来对其进行索引。每对之间用冒号:和逗号分隔键和值。必须用双引号引起来。与列表一样,我们可以通过以下方式打印字典:打印它的引用;字典将一组对象(键)映射到另一组对象(值); Python字典是唯一键与值的映射;字典是可变的,这意味着它们可以更改。该键指向可以是任意的Python值。字典是无序的,所以添加的按键并不一定反映什么样的顺序也可报告回来。“的顺序, 字体

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"]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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