【问题标题】:Change button text MessageBox更改按钮文本 MessageBox
【发布时间】:2018-10-24 19:12:02
【问题描述】:

使用来自How can I create a simple message box in Python?answer,我创建了一个是/否/取消弹出框:

>>> import ctypes
>>> ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 3)

看起来像这样:

我想知道您是否可以更改按钮的默认文本“是”、“否”和“取消”?我知道我可以使用tkinter 来执行此操作,但他们是使用此ctypes 实现的快速解决方法吗?

【问题讨论】:

  • 我的预测是,要做到这一点,你会发现自己陷入了win32 api地狱。使用 python gui 库可能会更容易,您的解决方案将是跨平台启动。就 tkinter 而言,有 this(尽管警告 effbot 已过时)。
  • MessageBox 提供了一组有限的按钮(及其文本),可通过参数获得。您只想更改它,还是在这些按钮上放置任何文本?

标签: python ctypes


【解决方案1】:

我认为@Paul Rooney 有一个很好的观点,即 tkinter 将是跨平台的。并且比调用消息框的开销要多一些。

查看MessageBox documentation from Microsoft(MessageBoxW 是 MessageBox 的 unicode 版本),您似乎有一组按钮可以是什么选项,这由函数调用中的第四个参数决定:

MB_ABORTRETRYIGNORE = 2
MB_CANCELTRYCONTINUE = 6
MB_HELP = 0x4000 = 16384
MB_OK   = 0
MB_OKCANCEL = 1
MB_RETRYCANCEL = 5
MB_YESNO = 4
MB_YESNOCANCEL = 3

如果这些选择对您有好处并且您是严格意义上的 Windows,那么这可能是您的赢家。这很好,因为您只有 ctypes 导入和实际的函数调用。虽然为了更安全一点,您应该考虑使用argtypes function from ctypes to make a function prototype

要以 tkinter 的方式进行操作,对于一个简单的消息框,您仍然可以使用大部分相同的选项(例如,是/否、确定/取消等)。如果您真的需要控制按钮文本,那么您必须布局一个基本表单。这是制作自己的表单的基本示例。我想你会觉得这很乏味。

from tkinter import Tk, LEFT, RIGHT, BOTH, RAISED, Message
from tkinter.ttk import Frame, Button, Style, Label


class Example(Frame):

    def __init__(self):
        super().__init__()   

        self.initUI()


    def initUI(self):

        self.master.title("Buttons")
        self.style = Style()
        self.style.theme_use("default")

        frame = Frame(self, relief=RAISED, borderwidth=1)

        message = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua... '

        lbl1 = Message(frame, text=message)
        lbl1.pack(side=LEFT, padx=5, pady=5) 

        frame.pack(fill=BOTH, expand=True)

        self.pack(fill=BOTH, expand=True)

        button1 = Button(self, text="button1")
        button1.pack(side=RIGHT, padx=5, pady=5)
        button2 = Button(self, text="second button")
        button2.pack(side=RIGHT)


def main():

    root = Tk()
    root.geometry("300x200+300+300")
    app = Example()
    root.mainloop()  

if __name__ == '__main__':
    main() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2012-05-27
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多