python 3.0 tkinter,如何重复一个函数,每个按钮按下一个返回值?

时间:2018-01-31 07:24:26

标签: python python-3.x function tkinter widget

正如您将看到以下代码,我是一名专业编码员,但我仍然坚持这个非常简单的任务。

代码的目的是随机生成一个字符串,将该字符串与列表中的字符串相匹配,然后返回字符串+属性,这样当它被按钮小部件拉动时,它就会显示整个卡片。 (名称和故事。)但是,它只生成相同的卡。我想让它在每次按下按钮时生成一张新卡。是的,我知道<Return>指的是回车键,这对我来说更容易确认它不起作用。

import _thread
import tkinter
import tkinter.messagebox
import random
import re
import time
import subprocess
from tkinter import *

top = tkinter.Tk()

def presentcard():
    tkinter.messagebox.showinfo("this is your card", what)    

thebutton = tkinter.Button(top, text = "Pull a card out.", command = presentcard)

class Allthecards:
    def __init__(self,name,story):
        self.name = name
        self.story = story

card1 = Allthecards("The Beast", "It eats things")
card2 = Allthecards("The Dog", "It barks at things")
card3 = Allthecards("The Jazz", "It hears things")
card4 = Allthecards("The Candles", "It feels things")
card5 = Allthecards("The Heat", "It burns things")

cardlist = ['card1','card2','card3','card4','card5']

def getcard():
    return(random.choice(cardlist))
thecard =  getcard()

def whichcard():
    if thecard == "card1":
        return(card1.name + " "+ card1.story)
    elif thecard == "card2":
        return(card2.name + " "+ card2.story)
    elif thecard == "card3":
        return(card3.name + " "+ card3.story)
    elif thecard == "card4":
        return(card4.name + " "+ card4.story)
    elif thecard == "card5":
        return(card5.name + " "+ card5.story)
    else:
        return thecard

what = whichcard()

thebutton.bind('<Return>',thecard)
thebutton.bind('<Return>',what)
thebutton.pack()    
top.mainloop()

1 个答案:

答案 0 :(得分:1)

您只调用getcard()方法一次。这就是你每次都看到同样信息的原因。

将您的presentcard()更改为以下内容。

def presentcard():
    global thecard
    thecard = getcard()
    what = whichcard()
    tkinter.messagebox.showinfo("this is your card", what)

它会给你想要的东西。

此外,如果您将参数传递给def whichcard()函数,例如def whichcard(thecard),则您不必在程序中的任何位置使用global thecard。因此,该功能将更改为

def presentcard():
    thecard = getcard()
    what = whichcard(thecard)
    tkinter.messagebox.showinfo("this is your card", what)

避免使用您在代码中使用的全局变量。重用这些功能变得很困难。只需将参数传递给函数。