python - tkinter.simpledialog.Dialog 使启动 tkinter.Button 处于按下状态

标签 python button dialog tkinter simpledialog

我在 Windows 7 上使用 Python 3.3。 我有一个 tkinter一个应用Button启动 tkinter.simpledialog.Dialog . 像这样(这是一个完整的、可运行的示例):

import tkinter
import tkinter.simpledialog

class Mainframe(tkinter.Frame):
    def __init__(self, parent):
        super(Mainframe, self).__init__(parent)
        self.parent = parent
        self.button = tkinter.Button(self, text="Open Dialog")
        open_dialog_op = lambda ev: self.open_dialog(ev)
        self.button.bind("<Button-1>", open_dialog_op)
        self.button.bind("<Return>", open_dialog_op)
        self.button.pack(side=tkinter.LEFT)

    def open_dialog(self, event):
        dialog = tkinter.simpledialog.Dialog(self.parent, "My Dialog")
        self.button.config(relief=tkinter.RAISED)  # does not help!

root = tkinter.Tk()
Mainframe(root).pack()
root.mainloop()

行为:

  • 如果您关注“打开对话框” Button然后输入RETURN,一切正常
  • 如果您用鼠标单击 Button ,对话框显示一切正常,但是
  • 当对话框关闭时,“打开对话框” Button显示在 它是沮丧的( tkinter.SUNKEN ,如果我没记错的话?)状态。
  • (有趣的是,对话框打开时,Button 是 正常显示。 沮丧的表情只有在对话框关闭后才会出现。)
  • 我尝试通过简单地调用来修复问题 button.config(relief=tkinter.RAISED) ,但这不 在这种情况下似乎什么都不做。

(实际上,我的完整应用程序开始将按钮显示为按下状态 在点击后立即,不仅仅是在对话框再次关闭时。 我发现这更合乎逻辑: simpledialog本地事件循环获取所有事件,因为 simpledialog 是模态的;这可能包括 <ButtonRelease-1> Button 上的鼠标事件?)

问题:

  1. 为什么会这样?
  2. 为什么我的完整应用程序中的行为会有所不同?
  3. 如何避免或修复这两者?

最佳答案

它的发生是因为您部分覆盖了做正确事情的默认绑定(bind)。

如果您希望按钮在按钮激活 上执行功能,正确的方法是向按钮添加命令 选项。我使用“激活”而不是“按下”的原因是——正如您的代码所示——在 tk 中激活按钮的方法不止一种:按下按钮、按下回车键、按下加速键等。

您编写的代码不会替换相当大的一组默认绑定(bind)。 iCodez 的回答确实正确地修复了最明显的缺陷,但让默认绑定(bind)保持不变并使用 command= 将适用于您尚未测试的情况(例如,仅键盘操作)。

关于python - tkinter.simpledialog.Dialog 使启动 tkinter.Button 处于按下状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198422/

相关文章:

html - 增加按钮的可点击区域

android - 加载新屏幕时显示对话框

python - 绘制数据框中按分组的聚合

python - 为什么 matplotlib 没有属性 'pylab' ?

python - 使用 xlwt 卡住 excel 中的单元格

android - Appcompat按钮背景样式

python - 获取 python 字符串中字符集的位置

jquery - 更改 jQuery UI 按钮的颜色

vue.js - 如何阻止 vuetify v-bottom-sheet 或 (v-dialog) 阻止与主要内容的交互

android - 如何检测用户何时触摸对话框 fragment 外部?