属性错误:“功能”错误没有属性“播放”在tkinter和pygame上

问题描述

我是新手,我正在尝试制作一个程序,根据我得到的随机数播放不同的声音。我用tkinter制作了一个窗口。 这是我的程序。我不明白为什么命令.play()不起作用。我尝试将其作为def son1 (play):之类的属性来使用,但是它没有用。我尝试了很多事情,但是没有成功。而且我根本不是专业人士,我的英语也不太熟练。我住在法国,没有多少人能很好地进行编码,所以我尝试阅读该文档,但这太难了。无论如何,谢谢您的帮助。

import tkinter
from tkinter import messageBox
import pygame
import random

def son1 ():#function that plays a sound (son1)
    pygame.mixer.init()
    global son1
    son1 = pygame.mixer.sound("Gun_Cocking.wav")
    son1.play()
def son2 ():#function that plays a sound (son2)
    pygame.mixer.init()
    global son2
    son2 = pygame.mixer.sound("Gunshot.wav")
    son2.play()
def gachette():#if r=1 son2 plays,if r!=1 son1plays
    global son1,son2
    r=random.randint(1,6)
    if r==1:
        label1.configure(text="BAM! T'as tiré hahahaha,t'es ded!",font=("Comic Sans Ms",18),foreground="red")
        son2.play()
        bouton01.destroy()
    else:
        label1.configure(text="Clic! T'as survécu,tu continues hahaha" )
        son1.play()

fenetre=tkinter.Tk()
fenetre.title("La roulette russe")
fenetre.geometry("600x600")
fenetre.configure(background="black")
espace_dessin=tkinter.Canvas(fenetre,background="black",height=600,width=600)
espace_dessin.pack()
label0=tkinter.Label(fenetre,text="JEU DE LA ROULETTE RUSSE",font=("Arial",20),foreground="black")
label0.configure(background="white")
label0.pack()
label0.place(x=115,y=20)

label1=tkinter.Label(fenetre,text="T'es toujours vivant,félicitations...!",foreground="green")
label1.configure(background="black")
label1.pack()
label1.place(x=110,y=200)

label2=tkinter.Label(fenetre,text="Tu poses le bout du canon sur ta tempe et ...",foreground="grey")
label2.configure(background="black")
label2.pack()
label2.place(x=70,y=300)

bouton01=tkinter.Button(fenetre,text="Tirer",command=gachette,16),relief="groove")
bouton01.pack()
bouton01.place(x=260,y=350)


fenetre.mainloop()

这是我的错误消息:

Traceback (most recent call last):
  File "C:\MCNL\Apps\Maths\EduPython\App\lib\tkinter\__init__.py",line 1538,in __call__
    return self.func(*args)
  File "D:\Users\Diana VOLF\Desktop\rouletterusse\rouletterusse.py",line 27,in gachette
    son1.play()
AttributeError: 'function' object has no attribute 'play'

解决方法

函数son1son2和对象son1son2具有相同的名称。该功能覆盖了对象。您必须使用其他名称:

def son1():#function that plays a sound (son1)
    pygame.mixer.init()
    global sound1
    sound1 = pygame.mixer.Sound("Gun_Cocking.wav")
    sound1.play()
def son2 ():#function that plays a sound (son2)
    pygame.mixer.init()
    global sound2
    sound2 = pygame.mixer.Sound("Gunshot.wav")
    sound2.play()
def gachette():#if r=1 son2 plays,if r!=1 son1plays
    global sound1,sound2
    r=random.randint(1,6)
    if r==1:
        label1.configure(text="BAM! T'as tiré hahahaha,t'es ded!",font=("Comic Sans Ms",18),foreground="red")
        sound2.play()
        bouton01.destroy()
    else:
        label1.configure(text="Clic! T'as survécu,tu continues hahaha" )
        sound1.play()