当我单击按钮两次时程序停止

时间:2017-05-23 15:40:28

标签: python tkinter

from tkinter import *

def page2():
    root1.destroy()
    import page2

root1 = Tk()
root1.geometry("300x150+177+180")
Label(root1, text="Hi I am page 1").pack()
Button(root1, text="Page 2", command=page2).pack()
root1.mainloop()

和第2页:

from tkinter import *

def page1():
    root2.destroy()
    import page1

root2 = Tk()
root2.geometry("300x150+177+180")
Label(root2, text="Hi I am page 2").pack()
Button(root2, text="Page 1", command=page1).pack()
root2.mainloop()

该程序运行正常,但当您使用该按钮两次时,程序将停止。

1 个答案:

答案 0 :(得分:0)

如Kevin所述, CREATE TABLE dbo.PK_Test ( PK INT ,TXT VARCHAR(0032) ); BEGIN TRANSACTION INSERT INTO dbo.PK_Test VALUES(05, 'First'); COMMIT TRANSACTION; CREATE FUNCTION dbo.F_PK_Test() RETURNS INTEGER AS BEGIN DECLARE @Highest INTEGER -- Find the highest number SET @Highest = (SELECT TOP 1 PK FROM PK_Test ORDER BY PK DESC) -- Take 0 if there is none SET @Highest = ISNULL(@Highest, 0) -- Add 1 SET @Highest = (@Highest + 1); RETURN @Highest END; SELECT * FROM dbo.PK_Test; BEGIN TRANSACTION INSERT INTO Adhoc_Area.dbo.PK_Test (PK, Txt) VALUES (Adhoc_Area.dbo.F_PK_Test(), Adhoc_Area.dbo.F_PK_Test()); INSERT INTO Adhoc_Area.dbo.PK_Test (PK, Txt) VALUES (Adhoc_Area.dbo.F_PK_Test(), Adhoc_Area.dbo.F_PK_Test()); COMMIT TRANSACTION; SELECT * FROM dbo.PK_Test; 语句只导入一次。简单的解决方案是将import替换为import page2。但是每次切换页面时都会生成一个新的Python进程......

相反,您可以根据the structure shown here将应用的每个页面定义为一个类,并将它们保存在不同的文件中。

<强> page1.py

os.system("python page2.py")

<强> page2.py

import tkinter as tk

class Page1(tk.Frame):
    def __init__(self, controller):
        tk.Frame.__init__(self, controller)
        tk.Label(self, text="Hi I am page 1").pack()
        tk.Button(self, text="Page 2", 
                  command=lambda:controller.show_page("Page2")).pack()

控制器文件:

import tkinter as tk

class Page2(tk.Frame):
    def __init__(self, controller):
        tk.Frame.__init__(self, controller)
        tk.Label(self, text="Hi I am page 2").pack()
        tk.Button(self, text="Page 1", 
                  command=lambda:controller.show_page("Page1")).pack()