Копирование из ящика сообщений с помощью Tkinter

#python #tkinter

Вопрос:

Я написал генератор паролей с помощью Tkinter и установил messagebox всплывающее окно, которое появляется, когда данные для веб-сайта уже есть в базе данных. Есть ли опция, которая позволяет мне скопировать текст из всплывающего окна? Потому что эти пароли действительно длинные. Или мне нужно зайти в файл, в котором он сохранен, чтобы скопировать его?

 messagebox.showinfo(title=website, message=f" Email: {email}nPassword: {password}")
 

Комментарии:

1. Сделайте свое собственное всплывающее окно и используйте Text виджет вместо Label виджета.

2. @TheLizzard-это этикетка messagebox? Как я могу изменить его, чтобы я мог скопировать показанный текст? Можете ли вы привести мне пример?

3. @DaveMier88 Внутренне, я думаю messagebox , использует Label виджет, но вы не можете это изменить. Просто создайте свое собственное всплывающее окно с нуля.

4. @TheLizzard Как мне сделать это окно сообщений-всплывающее окно. Какие еще у меня есть варианты?

Ответ №1:

Попробуйте что-нибудь вроде этого:

 import tkinter as tk


class Popup:
    def __init__(self, title:str="Popup", message:str="", master=None):
        if master is None:
            # If the caller didn't give us a master, use the default one instead
            master = tk._get_default_root()

        # Create a toplevel widget
        self.root = tk.Toplevel(master)
        # A min size so the window doesn't start to look too bad
        self.root.minsize(200, 40)
        # Stop the user from resizing the window
        self.root.resizable(False, False)
        # If the user presses the `X` in the titlebar of the window call
        # self.destroy()
        self.root.protocol("WM_DELETE_WINDOW", self.destroy)
        # Set the title of the popup window
        self.root.title(title)

        # Calculate the needed width/height
        width = max(map(len, message.split("n")))
        height = message.count("n")   1
        # Create the text widget
        self.text = tk.Text(self.root, bg="#f0f0ed", height=height,
                            width=width, highlightthickness=0, bd=0,
                            selectbackground="orange")
        # Add the text to the widget
        self.text.insert("end", message)
        # Make sure the user can't edit the message
        self.text.config(state="disabled")
        self.text.pack()

        # Create the "Ok" button
        self.button = tk.Button(self.root, text="Ok", command=self.destroy)
        self.button.pack()

        # Please note that you can add an icon/image here. I don't want to
        # download an image right now.
        ...

        # Make sure the user isn't able to spawn new popups while this is
        # still alive
        self.root.grab_set()
        # Stop code execution in the function that called us
        self.root.mainloop()

    def destroy(self) -> None:
        # Stop the `.mainloop()` that's inside this class
        self.root.quit()
        # Destroy the window
        self.root.destroy()


def show_popup():
    print("Starting popup")
    Popup(title="title", message="Message on 1 line", master=root)
    print("Ended popup")
    print("Starting popup")
    Popup(title="title", message="MessagenOn 2 lines", master=root)
    print("Ended popup")

root = tk.Tk()
root.geometry("300x300")

button = tk.Button(root, text="Click me", command=show_popup)
button.pack()

root.mainloop()
 

Это просто простой класс, который ведет себя очень похоже messagebox.showinfo . Вы можете добавить значок, если хотите. Пожалуйста, обратите внимание, что некоторые функции отсутствуют, но они должны работать с вашим кодом.

Для получения дополнительной информации о функциях, которые я использовал, пожалуйста, прочитайте документы. Вот неофициальные из них.

Комментарии:

1. Спасибо за ваши усилия. Я попробую это завтра

2. @DaveMier88 Скажи мне, если у тебя есть какие-либо вопросы/это не работает. Я догадываюсь, но спокойной ночи.