在while循环中更改tkinter画布中的图像 [英] Changing image in tkinter canvas in while loop

查看:93
本文介绍了在while循环中更改tkinter画布中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码整体是此处.

我正在尝试使用tkinter的画布创建一个小游戏,使人们可以练习学习高音谱号上的音符.

Using tkinter's canvas, I am trying to create a small game that allows people to practice learning the notes on the treble clef.

最初显示随机笔记,用户必须选择正确的笔记.如果学生得到正确答案,我将无法编辑画布以显示新笔记的图像.

A random note is initially displayed and the user must select the correct note. I am unable to edit the canvas to display a new note's image if the student got the correct answer.

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

Can somebody please explain what the problem is with my code?

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的基本机制进行一些了解.阅读注释以获取提示,提示您自己的编码尝试出了什么问题.

Run the code below and try to understand what it does and how. It displays a random "note" out of five again and again when you press the button for the note displayed (else it prints the bad chosen note and waits until you get it right). I suppose that this is what you need. Your own scripting attempt shows that you have to put some work into your understanding of the basic mechanisms behind tkinter. Read the comments for hints what was wrong with your own coding attempt.

请注意,您必须自己扩展字典,以使按钮涵盖所有注释.

Notice the you have to extend the dictionaries yourself to have the full range of notes covered by the buttons.

隐藏"功能是,如果您不喜欢显示的:D,则可以使用右箭头键切换到下一个音符.

The "hidden" feature is that you can switch with the right arrow key to the next note if you don't like the one displayed :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()

附录:在此程序中要执行的下一件事情是,如果按下右侧的一个按钮,则可以播放显示的音符.

ADDENDUM: The next thing to implement in this program is to let the displayed note play if the right one button is pressed.

这篇关于在while循环中更改tkinter画布中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆