Python 3.4使用变量赋值变量

时间:2015-04-15 13:55:54

标签: python tkinter

这是一个相当简单的问题;

我知道你可以这样做:

foo = 1,
self.card1 = "This is card number %s." % (foo)

但是我试图将函数给出的变量赋给名称本身:

def card(foo):
  self.foo = foo
  self.usrCrdImg%self.foo = Image.open(self.crdStk[randint(1, 50)])
  self.usrCrdBg%self.foo = ImageTk.PhotoImage(usrCrdImg%self.foo)
  self.usrCrd%self.foo = tkinter.Label(root, image=usrCrdBg%self.foo)
  self.usrCrd%self.foo.image = self.usrCrdBg%self.foo

card(1)
#Should Execute like this
def card(1):
  self.usrCrdImg1 = Image.open(self.crdStk[randint(1, 50)])
  self.usrCrdBg1 = ImageTk.PhotoImage(usrCrdImg1)
  self.usrCrd1 = tkinter.Label(root, image=usrCrdBg1)
  self.usrCrd1.image = self.usrCrdBg1 

一旦我得到这个问题的答案,我还有另外一个问题要问。

这是我的代码

import tkinter
import winsound
from tkinter import *
from PIL import Image, ImageTk
from random import randint, randrange

class CardGame(tkinter.Frame):

  def __init__(self, root):

    tkinter.Frame.__init__(self, root)

    #define variables for cards
    self.crdImg = []
    usrStk = None
    cpuStk = None
    #define card images
    i = 1
    while i < 57:
      i = i + 1
      self.crdImg.append('img/cards/%s.png' % (i - 1))

    usrStk = self.crdImg[54]
    cpuStk = self.crdImg[55]

  def debug(card):
    self.card = card
    self.usrCrdImg%self.card = Image.open(self.crdStk[randint(1, 50)])
    self.usrCrdBg%self.card = ImageTk.PhotoImage(self.usrCrdImg%self.card)
    self.usrCrd%self.card = tkinter.Label(root, image=self.usrCrdBg%self.card)
    self.usrCrd%self.card.image = self.usrCrdBg%i
  def card(self):

    ###
    self.usrStk1 = self.crdImg[54]
    self.cpuStk1 = self.crdImg[55]
    ##
    self.usrCrdImg1 = Image.open(self.usrStk1)
    self.usrCrdBg1 = ImageTk.PhotoImage(self.usrCrdImg1)
    self.usrCrd1 = tkinter.Label(root, image=self.usrCrdBg1)
    self.usrCrd1.image = self.usrCrdBg1
    ##
    self.cpuCrdImg1 = Image.open(self.cpuStk1)
    self.cpuCrdBg1 = ImageTk.PhotoImage(self.cpuCrdImg1)
    self.cpuCrd1 = tkinter.Label(root, image=self.cpuCrdBg1)
    self.cpuCrd1.image = self.cpuCrdBg1

2 个答案:

答案 0 :(得分:5)

您要做的只是解决问题的最糟糕方式。一般来说,您不应该尝试动态生成变量名称。

最简单的解决方案是使用字典。像这样:

def debug(card):
    self.card = card
    self.usrCrd[self.card]["Img"] = ... 
    self.usrCrd[self.card]["Bg"] = ...

但是,更好的解决方案是使“卡”成为班级的实例。然后,您可以将这些属性存储为类的属性:

class Card(object):
    def __init__(self, background, image):
        self.bg = background
        self.img = image
        ...

...
self.usrCrd = Card(...)
self.cpuCrd = Card(...)

答案 1 :(得分:1)

如果绝对必须创建变量,例如。一个Tkinter按钮,使用类似:

vars = []
founditems = ['item', 'otheritem']
for i in founditems:
    vars.append(i)
for n in range(len(founditems)-1):
    exec('tkbutton' + vars[i] + '=' + 'Button(textvariable=tv' + vars[i] + ', command=lambda: buttoncommand(' + vars[i] + '))')

基本格式: exec(var + '=' + varvalue)

如果您只需要定义变量名称,只需执行exec('varname = ' + varvalue)