Python为随机选择的单词定义一个动作

时间:2014-07-17 18:09:27

标签: python random tkinter

我编写了一个脚本,它从元组中选择一个随机字母并将其放入tkinter标签中。现在我想为每个字母定义特定的操作,例如,"E"可能会播放一首歌。我怎么能做到这一点?

# -*- coding: cp1252 -*-
import pygame
import Tkinter as tk
from Tkinter import *
from functools import partial
import random

pygame.init()

label=tk.Label()
label.pack()

def knopf(label):
    WORDS=("A", "B", "C", "D", "E")
    label['text']=random.choice(WORDS)

button=tk.Button(text='Knopf', command=partial(knopf, label))
button.pack()

mainloop()

我试着像亚当·斯密那样做,但我总是得到一个错误。

# -*- coding: cp1252 -*-
import Tkinter as tk
from Tkinter import *
from functools import partial
import random
import pygame

pygame.init()

label=tk.Label()
label.pack()

def knopf(label):
    def do_a(): pass
    def do_b(): pass
    def do_c(): pass
    def do_d(): pass
    def do_e(): print("E")
    WORDS={"A":do_a, "B":do_b, "C":do_c, "D":do_d, "E":do_e}
    choice = random.choice(WORDS)
    label['text']=choice 
    WORDS[choice]()

button=tk.Button(text='Knopf', command=partial(knopf, label))
button.pack()

mainloop()

这是错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\tester.py", line 20, in knopf
choice = random.choice(WORDS)
File "C:\Python27\lib\random.py", line 273, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
KeyError: 3

1 个答案:

答案 0 :(得分:5)

为每个函数编写一个函数,并使用字典与下面的WORDS[choice]()一起发送到各种函数。

def knopf(label):
    def do_a(): pass
    def do_b(): pass
    def do_c(): pass
    def do_d(): pass
    def do_e(): play_song()
    WORDS={"A":do_a, "B":do_b, "C":do_c, "D":do_d, "E":do_e}
    choice = random.choice(list(WORDS)) # make the choice
    label['text']=choice # set the label
    WORDS[choice]() # do the action