运行以下代码并尝试理解它的作用和原理。当你按下显示的音符的按钮时,它会无限次地随机显示五个音符中的一个(否则它会打印出错误的选择,并等待你做出正确的选择)。我想这就是你所需要的。你自己的脚本尝试表明你需要投入一些工作来理解 tkinter 背后的基本机制。阅读注释以获取关于你自己编码方案有什么问题的提示。
请注意,你必须自己扩展字典以涵盖按钮覆盖的所有音符范围。
“隐藏”的功能是,如果你不喜欢显示的音符,你可以使用右箭头键切换到下一个音符 :D 。
from random import randint
from tkinter import *
import tkinter as tk
from PIL import ImageTk, Image
root = Tk()
root.wm_attributes("-topmost", 1)
root.geometry('{}x{}'.format(1100, 720))
canvas = Canvas(root, width=950, height=700)
def client_exit():
''' Quit Button '''
exit()
def pickNote(value):
''' Changes noteChosen var to the note's button pressed '''
global correctNote
noteChosen = value
if noteChosen == correctNote:
print("SUCCESS !!!")
displayRandomNote(None)
else:
print( " :( ", noteChosen, " :( ")
quitButton = tk.Button(text="Quit", command=client_exit)
quitButton.place(x=480, y=480)
aButton = tk.Button(text="A", command=lambda *args: pickNote("A"))
aButton.config(height=3, width=9)
aButton.place(x=190, y=400)
bButton = tk.Button(text="B", command=lambda *args: pickNote("B"))
bButton.config(height=3, width=9)
bButton.place(x=280, y=400)
cButton = tk.Button(text="C", command=lambda *args: pickNote("C"))
cButton.config(height=3, width=9)
cButton.place(x=370, y=400)
dButton = tk.Button(text="D", command=lambda *args: pickNote("D"))
dButton.config(height=3, width=9)
dButton.place(x=460, y=400)
eButton = tk.Button(text="E", command=lambda *args: pickNote("E"))
eButton.config(height=3, width=9)
eButton.place(x=550, y=400)
fButton = tk.Button(text="F", command=lambda *args: pickNote("F"))
fButton.config(height=3, width=9)
fButton.place(x=640, y=400)
gButton = tk.Button(text="G", command=lambda *args: pickNote("G"))
gButton.config(height=3, width=9)
gButton.place(x=730, y=400)
noteFiles = { 1:'1.png', 2:'2.png', 3:'3.png', 4:'4.png', 5:'5.png' }
notes = { 1:'A' , 2:'B' , 3:'C' , 4:'D' , 5:'E' }
randomNote = randint(1, 5)
path = noteFiles[randomNote]
correctNote = notes[randomNote]
img = Image.open(path)
tk_img = ImageTk.PhotoImage(img)
imageOnCanvas = canvas.create_image(130, 150, image=tk_img)
canvas.pack()
def displayRandomNote(event):
global canvas
global imageOnCanvas
global tk_img
global correctNote
global notes
randomNote = randint(1, 5)
path = noteFiles[randomNote]
correctNote = notes[randomNote]
img = Image.open(path)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig(imageOnCanvas, image=tk_img)
canvas.pack()
root.bind('<Right>', displayRandomNote)
root.mainloop()
附录:此程序中需要实现的下一步是,如果按下了正确的按钮,则让显示的音符播放。
![5.png](https://istack.dev59.com/6NP0k.webp)
mainloop()
之后的代码都不会在程序退出之前执行,如果有的话。您需要安排您的代码在循环期间执行 - 例如按键绑定、按钮上的command=
选项或其他各种方式。您提供的信息远远不足以得到一个具体的答案,因为我们不知道您的程序应该如何工作。 - jasonharperwhile True
循环不兼容。 - Taku