显示框后如何调用函数?

时间:2019-07-11 13:55:22

标签: python tkinter

我想在代码中进行语音识别。我在此代码中使用了多个框架。起始页实际上仅是用于启动应用程序的菜单。在startPage中有一个用于启动应用程序的按钮。之后,将出现PageOne。但是我想在第一页做语音识别。如果我调用了Speechh函数,则在运行代码后,语音识别将立即开始。我想问我如何做才能使语音识别从单击开始页面中的按钮后的第一页开始?

import tkinter as tk   # python3
#import Tkinter as tk   # python
from PIL import ImageTk, Image
import speech_recognition as sr
import threading, time
import sys


TITLE_FONT = ("Helvetica", 18, "bold")
str=""
arr=["E", "F P", "T O Z", "L P E D", "P E C F D", "E D F C Z P", "F E L O P Z D", "D E F P O T E C", "L E F O D P C T", "F D P L T C E O", "P E Z O L C F T D"]
page=["PageOne", "PageTwo"]

def speechh():
    # while True:
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)

    # Speech recognition using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")
        # instead of r.recognize_google(audio)
        str = r.recognize_google(audio)
        print(str)
        print("You said: " + str)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

    asd = ""

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # self.attributes("-fullscreen", True)
        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        # sys.stdin.read(1)
        for F,geometry in zip((StartPage, PageOne, PageTwo), ('1940x800', '1940x800', '1940x800')):
            # sys.stdin.read(1)
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            # store the frame and the geometry for this frame
            self.frames[page_name] = (frame, geometry)

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame("StartPage")
    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame, geometry = self.frames[page_name]
        # change geometry of the window
        self.update_idletasks()
        self.geometry(geometry)
        frame.tkraise()
    def on_start(self):
        # for x in page:
        # self.show_frame("PageOne")
        # self.after_idle(speechh)
        for x in page:
            self.show_frame(x)
            speechh()
        # time.sleep(10)
        # speechh()
        # sys.stdin.read(1)
        # self.show_frame("PageTwo")
        # self.after_idle(speechh)


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        fname = "coba2.gif"
        cv = tk.Canvas(self, bg="pink")
        cv.pack(side='top', fill='both', expand='yes')
        img = ImageTk.PhotoImage(file = "C:\\Users\\Shintia Tamara\\PycharmProjects\\ProjectAI\\coba2.gif")
        cv.create_image(10, 10, image = img, anchor = "nw")
        btn1 = tk.Button(cv, text="QUIT", height=2, width=20, bg="#686DCE", borderwidth=0,
                      fg="white", font=('Sans', '10', 'bold'))
        btn1.pack(side='right', padx=50, pady=50, anchor='se')
        btn2 = tk.Button(cv, text="START", height=2,command=controller.on_start, width=20, bg="#686DCE", borderwidth=0, fg="white",
                      font=('Sans', '10', 'bold'))
        btn2.pack(side='right', padx=5, pady=50, anchor='se')


class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        letter = tk.Label(self, text=arr[0], font=("Helvetica", 432))
        letter.pack(side="bottom", expand="YES")


class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        letter = tk.Label(self, text="F P", font=("Helvetica", 216))
        letter.pack(side="bottom", expand="YES")

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

1 个答案:

答案 0 :(得分:2)

最后删除语音通话,将command=lambda: controller.show_frame("PageOne"),更改为command=controller.on_start,,并在show_frame方法附近添加此方法:

def on_start(self):
    self.show_frame("PageOne")
    speech()