2016-04-12 47 views
1

我想創建多個窗口使用tkinter,但我目前沒有成功......當我創建一個子窗口並在其上放置一個按鈕時,該按鈕創建在父窗口!Tkinter - 在錯誤的屏幕上創建按鈕

from tkinter import * 

class Login_screen(Frame): 
    def __init__(self,master): 
     Frame.__init__(self, master) 
     self.grid() 
     self.button1 = Button(text = "Open",command = lambda: self.open_login()) 
     self.button1.grid() 

    def open_login(self): 
     self.root2 = Toplevel() 
     self.root2.geometry("400x200") 
     self.app2 = Main_screen(self.root2) 

class Main_screen(Frame): 
    def __init__(self,master): 
     Frame.__init__(self,master) 
     self.grid() 
     self.button = Button(text = "Close",command = lambda: self.close_windows()) 
     self.button.grid() 

    def close_windows(self): 
     self.grid_forget() 

root = Tk() 
root.geometry("800x600") 
app = Login_screen(root) 
root.mainloop() 

回答

2

您需要與主論點提供Button()

self.button = Button(master = self, text = "Close",command = lambda: self.close_windows()) 

master是第一個參數的構件,因此它也可以做到通過:Button(self, text=...)

這是很好的做法你應該養成明確提供master的習慣,否則Tk默認這個參數爲None,並將它放在根窗口上。