当我按下python按钮时如何调用opencame函数

问题描述

我有一个dashboard.py文件,运行该文件时会显示一个包含按钮的屏幕,如何在屏幕上显示该按钮,单击它会打开文件face_detect,谢谢大家

from tkinter import *
class DashboardWindow():
    def __init__(self):
        self.win = Tk()
        # reset the window and background color
        self.canvas = Canvas(self.win,width=600,height=500,bg='white')
        self.canvas.pack(expand=YES,fill=BOTH)
        # show window in center of the screen
        width = self.win.winfo_screenwidth()
        height = self.win.winfo_screenheight()
        x = int(width / 2 - 600 / 2)
        y = int(height / 2 - 500 / 2)
        str1 = "600x500+" + str(x) + "+" + str(y)
        self.win.geometry(str1)

        # disable resize of the window
        self.win.resizable(width=False,height=False)

        # change the title of the window
        self.win.title("WELCOME | Login Window | ADMINISTRATOR")
        self.win.mainloop()`enter code here`

def opencame(self):
    import  face_detect
button = Button(text="OpenCame",font='Courier 15 bold',command = opencame())
button.pack()

解决方法

尝试

from tkinter import *
def opencame():
    import  face_detect
button = Button(text="OpenCame",font='Courier 15 bold',command = opencame)
button.pack()
button.mainloop()
,

首先,您应该将command=opencame()更改为command=opencame

第二,它实际上取决于face_detect.py的编写方式。例如,如果face_detect.py如下所示:

# face_detect.py
import tkinter as tk

win = tk.Toplevel()
win.transient(win.master)

tk.Label(win,text='welcome to face detection',font='Helvetica 16 bold').pack()
tk.Button(win,text='Quit',command=win.destroy).pack()

win.grab_set()
win.wait_window()

如果首先点击OpenCame按钮,则将显示一个窗口。首先 。但是,由于模块已经加载,再次单击该按钮将不会显示任何窗口。

但是,如果您按以下方式重写face_detect.py

# face_detect.py
import tkinter as tk

def open_window():
    win = tk.Toplevel()
    win.transient(win.master)

    tk.Label(win,font='Helvetica 16 bold').pack()
    tk.Button(win,command=win.destroy).pack()

    win.grab_set()
    win.wait_window()

并如下重写opencame()

def opencame(self):
    import face_detect
    face_detect.open_window()

然后,只要单击OpenCame按钮,就会显示一个窗口。