【问题标题】:Retrieving information from callback functions in Tkinter从 Tkinter 中的回调函数中检索信息
【发布时间】:2020-03-31 22:48:04
【问题描述】:

(上下文)我正在创建一个游戏,它涉及通过选择 python 从音频文件列表中随机生成的音符来重新创建旋律。我在从 Tkinter 的回调函数中检索和使用信息时遇到问题。相关代码如下:

def PlayRandomNote(self):
    NoteIndex = random.randint(0, 6)
    Note = ListOfSamples[NoteIndex]
    self.PlayFile(Note)
    return Note

def Screen3(self,Melody):
    GuessedMelody = []
    self.PlayNote = ttk.Button(self.Main, text = "Play random note", command = self.PlayRandomNote)
    self.Question = Label(self.Main, text = "Was that the correct note?", bg = "black", fg = "white")
    self.Yes = ttk.Button (self.Main, text = "Yes", command = lambda: self.ThreeToFour(Melody, GuessedMelody))
    for Widget in self.Main.winfo_children():
        Widget.pack()

(问题)我希望这样当用户按下“是”按钮时,按下“播放随机音符”按钮播放的最后一个音符被添加到我的 GuessedMelody 列表中,然后这个列表被添加为我的 ThreeToFour 函数的参数(从当前屏幕转换到下一个屏幕的函数)。有没有办法做到这一点?

【问题讨论】:

    标签: python-3.x button tkinter callback


    【解决方案1】:

    不,你必须使用你的对象来保存信息,而不是传递所有东西。下面的代码是您应该瞄准的粗略猜测。没有其他代码很难说。通过似乎更有效率,但它不起作用,在python中也没有必要。例如,您在 PlayRandomNote(self) 中返回便笺...它无处可去,因此您必须为它准备好一个变量并将其分配给该变量。

    def PlayRandomNote(self):
        NoteIndex = random.randint(0, 6)
        Note = ListOfSamples[NoteIndex]
        self.PlayFile(Note)
        self.curent_random_note
    
    def Screen3(self):
        self.PlayNote = ttk.Button(self.Main, text = "Play random note", command = self.PlayRandomNote)
        self.Question = Label(self.Main, text = "Was that the correct note?", bg = "black", fg = "white")
        self.Yes = ttk.Button (self.Main, text = "Yes", command =  self.ThreeToFour)
        for Widget in self.Main.winfo_children():
            Widget.pack()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多