【问题标题】:Python tkinter, how to disable background buttons from being clickedPython tkinter,如何禁用背景按钮被点击
【发布时间】:2012-06-22 19:17:31
【问题描述】:

当打开一个新的 tkinter 窗口时,我只希望用户能够点击新窗口上的按钮。他们应该不能从属于应用程序的其他窗口单击按钮。我将如何做到这一点?

这是我的代码片段:

def exportEFS(self):
  self.exportGUI = Toplevel()
  Button(self.exportGUI, text='Backup', command=self.backup).pack(padx=100,pady=5)
  Button(self.exportGUI, text='Restore', command=self.restore).pack(padx=100,pady=5)

def backup(self):
  self.backupWindow = Toplevel()

  message = "Enter a name for your Backup."

  Label(self.backupWindow, text=message).pack()

  self.entry = Entry(self.backupWindow,text="enter your choice")
  self.entry.pack(side=TOP,padx=10,pady=12)

  self.button = Button(self.backupWindow, text="Backup",command=self.backupCallBack)
  self.button.pack(side=BOTTOM,padx=10,pady=10)

在此片段中,一旦打开了 backupWindow,exportGUI 将保持打开状态,但在打开 backupWindow 时用户应该无法单击“备份”或“恢复”。

谢谢!

【问题讨论】:

    标签: python button background window tkinter


    【解决方案1】:

    您需要在 TopLevel 窗口上调用 grab_set,以便将所有键盘和鼠标事件发送到该窗口。

    def exportEFS(self):
      self.exportGUI = Toplevel()
      Button(self.exportGUI, text='Backup', command=self.backup).pack(padx=100,pady=5)
      Button(self.exportGUI, text='Restore', command=self.restore).pack(padx=100,pady=5)
    
    def backup(self):
      self.backupWindow = Toplevel()
      self.backupWindow.grab_set()
    
      message = "Enter a name for your Backup."
    
      Label(self.backupWindow, text=message).pack()
    
      self.entry = Entry(self.backupWindow,text="enter your choice")
      self.entry.pack(side=TOP,padx=10,pady=12)
    
      self.button = Button(self.backupWindow, text="Backup",command=self.backupCallBack)
      self.button.pack(side=BOTTOM,padx=10,pady=10)
    

    【讨论】:

      【解决方案2】:

      您可以做的是将状态设置为禁用。因此:

      self.button.config(state="disabled")
      

      要启用它,您只需使用:

      self.button.config(state="normal")
      

      但是,您必须先将按钮分配给变量,如下所示:

      self.backup=Button(self.exportGUI, text='Backup', command=self.backup)
      self.backup.pack(padx=100,pady=5)
      self.restore=Button(self.exportGUI, text='Restore', command=self.restore)
      self.restore.pack(padx=100,pady=5)
      

      因此您可以使用以下方法禁用这些:

      self.backup.config(state="disabled")
      self.restore.config(state="disabled")
      

      并重新启用:

      self.backup.config(state="normal")
      self.restore.config(state="normal")
      

      但是请注意,当按钮被禁用时,不能通过代码或通过用户使用它来更改该按钮。这意味着如果您想更改该按钮的文本,则必须在更改之前将按钮的状态更改为"normal"(如果它已经不在该状态,默认情况下,所有小部件都在首次创建时的状态)。

      干杯:)

      【讨论】:

        猜你喜欢
        • 2014-12-06
        • 2020-09-09
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 2021-11-27
        • 2020-11-07
        • 1970-01-01
        相关资源
        最近更新 更多