简体   繁体   中英

Python | (Tkinter) only shows text when button is pressed

So I made a button to copy something to clipboard, but the button itself is always showing, but the text on it only when its pressed, how to fix it? (Here the part with the button code:)

canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.pack()


def copy_button():
    clip = tk.Tk()
    clip.withdraw()
    clip.clipboard_clear()
    clip.clipboard_append(pw)
    clip.destroy()


button1 = tk.Button(text="Copy to Clipboard", command=copy_button, bg="grey", fg="white", font=("Helvetica", 12, "bold"))
canvas1.create_window(150, 150, window=button1)

Your disappearing text issue does not appear in Linux OS but I suspect your issue is related to your button1 = tk.Button(....) statement.

The first argument to a tk.Button widget must be its parent (see this link on this requirement) and not a keyword/option.

Try button1 = tk.Button(canvas1, text="Copy to Clipboard", ....) . Doing so, you define the tk.Button to be a child of the tk.Canvas widget.

If you are putting more than a button in the canvas, you might want to consider:

  1. defining a tk.Frame to be a child of the tk.Canvas (eg frame1=tk.Frame(canvas1) ),
  2. replace window=button1 with window=frame1 ,
  3. letting button1 to be a child of frame1, eg button1 = tk.Button(frame1, text="Copy to Clipboard", ....)

Do let me know if this answer addresses your issue.

Other suggestion:

You can remove clip = tk.Tk() , clip.withdraw() , clip.destroy() and replace the clip term in clip.clipboard_clear() and clip.clipboard_append(pw) with root . Here, I assume that you had earlier defined root = tk.Tk() at the start of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM