Home  >  Q&A  >  body text

python - 【:-D Tkinter 中 withdraw的正确使用姿势

如何实现点击button之后 显示一个新的窗口并且使button那个窗口直接消失
先贴上代码

    #coding:utf-8
    import Tkinter as tk
    from Tkinter import *
    import tkMessageBox
  
   
    root = tk.Tk()
    root.title('Test')
    e = StringVar()
  
  
    def callback():
         #tkMessageBox.showinfo('title','hello world')
          entry = Entry(root,textvariable = e)
          e.set('请输入')
          entry.pack()
 
  
    def bnt():
          Button(root,text = '确认使用',fg='red',bd = 2,width =28,
          command = callback).pack()
          root.withdraw()
    bnt()
    root.mainloop()
    

但比较蛋疼的是。。用了withdraw之后button窗口就直接匿了。。。点都点不了

伊谢尔伦伊谢尔伦2742 days ago1030

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 17:35:00

    Same as shomy, I rarely use Tkinter, so I wrote a PyQt4 version. You can try it, and it runs without any problem in my own test

    # coding:utf-8
    
    from PyQt4.QtGui import *
    
    # 点击后需要显示的窗口
    class Window(QWidget):
        def __init__(self, parent=None):
            super(Window, self).__init__(parent)
            self.resize(400, 200)
            self.setWindowTitle("I am the new Window")
    
        def handleTrigger(self):
            # 如果当前为隐藏状态,则显示
            if not self.isVisible():
                self.show()
    
    # 按钮
    class Btn(QToolButton):
    
        def __init__(self, parent=None):
            super(Btn, self).__init__(parent)
            self.resize(300, 100)
    
        def handleClick(self):
            # 如果当前为显示状态,则隐藏
            if self.isVisible():
                self.hide()
    
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        b = Btn()
        w = Window()
        # 窗口初始化为隐藏
        w.hide()
        # 点击时,触发新窗口的handleTrigger事件
        b.clicked.connect(w.handleTrigger)
        # 点击时,触发Button自己的handleClick事件
        b.clicked.connect(b.handleClick)
        b.show()
        app.exec_()
        

    PS: If there are no special requirements, it is recommended to use PyQt4/PyQt5 for development. Reasons:
    1) With the help of Qt’s powerful class library, PyQt can do many things, such as graphics drawing, XML parsing, Network programming, database reading and writing, etc. In other words, PyQt is not only a GUI library, but also includes non-GUI parts.
    2) With the help of Qt Designer, you can drag and drop the graphical interface part, which is very efficient.
    3) Strong community support. For example, there is a Python IDE developed based on PyQt. This is more popular in the open source community than Tkinter currently seems to be.

    reply
    0
  • Cancelreply