简体   繁体   English

Python | (Tkinter)仅在按下按钮时显示文本

[英]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. Linux 操作系统中没有出现您消失的文本问题,但我怀疑您的问题与您的button1 = tk.Button(....)语句有关。

The first argument to a tk.Button widget must be its parent (see this link on this requirement) and not a keyword/option. tk.Button小部件的第一个参数必须是其父级(请参阅此链接了解此要求),而不是关键字/选项。

Try button1 = tk.Button(canvas1, text="Copy to Clipboard", ....) .尝试button1 = tk.Button(canvas1, text="Copy to Clipboard", ....) Doing so, you define the tk.Button to be a child of the tk.Canvas widget.这样做,您将tk.Button定义为tk.Canvas小部件的子级。

If you are putting more than a button in the canvas, you might want to consider:如果您在 canvas 中放置了多个按钮,您可能需要考虑:

  1. defining a tk.Frame to be a child of the tk.Canvas (eg frame1=tk.Frame(canvas1) ),将 tk.Frame 定义为tk.Frame的子tk.Canvas (例如frame1=tk.Frame(canvas1) ),
  2. replace window=button1 with window=frame1 ,window=frame1替换window=button1
  3. letting button1 to be a child of frame1, eg button1 = tk.Button(frame1, text="Copy to Clipboard", ....)让 button1 成为 frame1 的子对象,例如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 .您可以删除clip = tk.Tk()clip.withdraw()clip.destroy()并将 clip.clipboard_clear( clip.clipboard_clear()和 clip.clipboard_append clip.clipboard_append(pw)中的clip项替换为root Here, I assume that you had earlier defined root = tk.Tk() at the start of your code.在这里,我假设您之前在代码开头定义了root = tk.Tk()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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