python - 在 while 循环中更改 tkinter Canvas 中的图像

标签 python python-3.x tkinter python-imaging-library tkinter-canvas

我的全部代码是 here .

使用 tkinter 的 Canvas ,我正在尝试创建一个小游戏,让人们练习学习高音谱号上的音符。

最初会显示一个随机音符,用户必须选择正确的音符。如果学生得到正确答案,我无法编辑 Canvas 以显示新笔记的图像。

有人可以解释一下我的代码有什么问题吗?

while True:
    randomNote = randint(0, 11)
    path = noteFiles[randomNote]
    correctNote = notes[randomNote]
    img = Image.open(path)
    tk_img = ImageTk.PhotoImage(img)
    canvas.create_image(505, 200, image=tk_img)

    root.mainloop()
    if correctNote == noteChosen:
        ''' User got last note right '''
        canvas.delete("all")

最佳答案

运行下面的代码并尝试理解它的作用和方式。当您按下所显示音符的按钮时,它会一次又一次地显示五个中的随机“音符”(否则它会打印出错误的选择音符并等到您正确为止)。我想这就是你所需要的。您自己的脚本编写尝试表明您必须花一些功夫来理解 tkinter 背后的基 native 制。阅读评论以提示您自己的编码尝试出了什么问题。

请注意,您必须自己扩展词典才能让按钮涵盖所有范围的注释。

“隐藏”功能是,如果您不喜欢显示的音符,可以使用向右箭头键切换到下一个音符 :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)) # window size
# canvas = Canvas(root, bd=0, highlightthickness=0)
canvas = Canvas(root, width=950, height=700)
# canvas.pack()

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, " :( ")

# Creates button to exit the program
quitButton = tk.Button(text="Quit", command=client_exit)
quitButton.place(x=480, y=480)

# Creates buttons for various notes
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) # position of image center in window
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) # change the displayed picture
    canvas.pack()

    # userResponse = input("Which note?\n           ")
    # if userResponse == correctNote:
    #     print("                      SUCCESS :) !!!")
    #     print("(switch focus)")
    # else:
    #     print("                      TRY ANOTHER ONE ...")
    #     print("(switch focus)")

# print("Switch window focus to CONSOLE to input the answer. ")
# print("Swicht window focus to IMAGE (press right arrow key for a Note)")

root.bind('<Right>', displayRandomNote) # on right arrow key display random note

root.mainloop()

附录:此程序中接下来要实现的是,如果按下右侧的一个按钮,则让显示的音符播放。

1.png 2.png 3.png 4.png 5.png

关于python - 在 while 循环中更改 tkinter Canvas 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43691102/

相关文章:

python - 根据键修剪有序字典?

python - Tkinter - 在使用任何小部件之前最大化和最小化窗口,在我使用它们时隐藏小部件

python - Matplotlib:使用颜色图显示状态(axvspan 或 bar?)

python - Python 是否提供 "free"默认迭代器?

python - 使用tensorflow求解代数时,训练后所有变量都变成了nan

python-3.x - AWS Redshift : How to describe a library created in redshift?

python 3 : Why does __spec__ work?

python - 如何通过按键事件绑定(bind)更新 tkinter 类中的图像?

python - ttk.Combobox 状态为只读且未聚焦时出现故障

python - 在 Python OpenCV 中查找最大和第二大面积轮廓