2017-03-15 77 views
0

當使用python 3.6和tkinter創建第二個窗口時,它不負責任。我使用的是OS X 10.11.6。 在其他系統(如Ubuntu)中,此代碼正常工作。我不能使用tkinter在os上創建第二個窗口x

from tkinter import * 

class win2: 

    def __init__(self): 
     self.root = Tk() 
     self.root.mainloop() 

class win1: 

    def __init__(self): 
     self.root = Tk() 

     self.button = Button(self.root) 
     self.button.bind('<Button-1>', self.buttonFunc) 
     self.button.pack() 

     self.root.mainloop() 

    def buttonFunc(self, event): 
     windows2 = win2() 

if __name__ == "__main__": 
    window1 = win1() 
+1

我覺得你正在接近錯誤的問題。你的tkinter GUI應該只有1個主循環。你的'win2'類沒有做任何事情。我建議找到一個簡單的tkinter示例並從那裏開始工作。另外,PyQt是GUI的另一個選項 –

回答

1

這是一個非常糟糕的主意,多次使用Tk()更在你的程序。使用它來創建根窗口,然後使用Toplevel()來創建任何其他窗口。

def buttonFunc(self, event): 
    Toplevel(self.root) 

這就是說,它仍然看起來像你試圖做一些艱難的事情。你能更好地描述你的最終目標是什麼嗎?

要進行模態窗口(彈出)使用這樣的代碼:

try: #python3 imports 
    import tkinter as tk 
except ImportError: #python3 failed, try python2 imports 
    import Tkinter as tk 

class Main(tk.Frame): 
    def __init__(self, master=None, **kwargs): 
     tk.Frame.__init__(self, master, **kwargs) 

     lbl = tk.Label(self, text="this is the main frame") 
     lbl.pack() 

     btn = tk.Button(self, text='click me', command=self.open_popup) 
     btn.pack() 

    def open_popup(self): 
     print("runs before the popup") 
     Popup(self) 
     print("runs after the popup closes") 

class Popup(tk.Toplevel): 
    """modal window requires a master""" 
    def __init__(self, master, **kwargs): 
     tk.Toplevel.__init__(self, master, **kwargs) 

     lbl = tk.Label(self, text="this is the popup") 
     lbl.pack() 

     btn = tk.Button(self, text="OK", command=self.destroy) 
     btn.pack() 

     # The following commands keep the popup on top. 
     # Remove these if you want a program with 2 responding windows. 
     # These commands must be at the end of __init__ 
     self.transient(master) # set to be on top of the main window 
     self.grab_set() # hijack all commands from the master (clicks on the main window are ignored) 
     master.wait_window(self) # pause anything on the main window until this one closes 

def main(): 
    root = tk.Tk() 
    window = Main(root) 
    window.pack() 
    root.mainloop() 

if __name__ == '__main__': 
    main() 
+0

我想爲我的應用程序創建設置窗口。這裏是我的完整代碼的鏈接https://codeshare.io/GqANWx –

+0

這是一個'模態窗口'。我編輯了我的答案,告訴你如何做到這一點。我建議你也按照我的主角進行子類化,而不是像'self.root'這樣的屬性。 – Novel

+1

@МихайлоПилипишин請不要讓人們爲你做所有事情,並給他們你的完整代碼。這不是什麼... – abccd

0

此代碼對我的作品。

from tkinter import * 

class win1: 

    def __init__(self): 
     root = Tk() 
     button = Button(root) 
     button.bind('<Button-1>', self.buttonFunc) 
     button.pack() 
     root.mainloop() 

    def buttonFunc(self, event): 
     window2 = win2() 

class win2(win1): 

    def __init__(self): 
     top = Toplevel() 

if __name__ == "__main__": 
    window1 = win1()