Python / Tkinter-选择并复制所有文本内容,然后单击按钮从其他功能复制到剪贴板

问题描述

最近几天,我才开始自学Python,以进行一些应用程序编程,并且以前有使用PHP开发网站的经验。我一直在构建一个程序,该程序将解析信息列表,构建收集的变量数组,然后在新的Tkinter顶级窗口中使用这些变量加载并填充html模板。新窗口由在根窗口中的菜单栏命令调用的函数创建。它所包含的只是一个带有滚动条和一些按钮的文本框,应该允许用户选择所有文本,将其复制到剪贴板,然后关闭窗口。

我遇到的问题,而且我确信这可能是对精通Python的人的简单解决方案,因为我不知道如何在从其他内部调用select和copy函数时正确引用所有内容职能。如果我像只在一个窗口外工作一样精简代码,一切都会按预期进行:

import tkinter as tk

def clipit():
    textpop.clipboard_clear()
    textpop.event_generate("<<TextModified>>")
    textpop.clipboard_append(textarea.get('1.0','end'))
    textpop.update()
    
def textselect():
    textpop.event_generate("<<TextModified>>")
    textarea.tag_add('sel',"1.0",'end-1c')

textpop = tk.Tk()
textarea = tk.Text(textpop,wrap="none")
textarea.pack(side="left",fill="both",padx=20,pady=20)
textarea.insert("1.0","This is a test - Try to select all and copy!")
exitbutton = tk.Button(textpop,text="Close",command = textpop.destroy)
exitbutton.pack(side="right",padx=(5,20),pady=(0,20))
copybutton = tk.Button(textpop,text="Copy",command = clipit)
copybutton.pack(side="right",padx=5,20))
selectbutton = tk.Button(textpop,text="Select All",command = textselect)
selectbutton.pack(side="right",20))
textarea.focus()
textpop.mainloop()

如果我尝试执行相同的操作,但是从某个函数(textpop = tk.Toplevel())中执行该操作,它将不再起作用。我试图传递各种对函数的引用(父,小部件等)并相应地修改函数代码,但是还没有运气。例如:

import tkinter as tk

def clipit(parent,textwidget):
    parent.clipboard_clear()
    parent.event_generate("<<TextModified>>")
    parent.clipboard_append(textwidget.get('1.0','end'))
    parent.update()
    
def textselect(parent,textwidget):
    parent.event_generate("<<TextModified>>")
    parent.textwidget.tag_add('sel','end-1c')

def textwindow(title,content):
    textpop = tk.Toplevel()
    textpop.title(title)
    textarea = tk.Text(textpop,wrap="none")
    textarea.pack(side="left",pady=20)
    textarea.insert("1.0",content)
    exitbutton = tk.Button(textpop,command = textpop.destroy)
    exitbutton.pack(side="right",20))
    copybutton = tk.Button(textpop,command = lambda: clipit(textpop,textarea))
    copybutton.pack(side="right",20))
    selectbutton = tk.Button(textpop,command = lambda: textselect(textpop,textarea))
    selectbutton.pack(side="right",20))
    textarea.focus()
    textpop.mainloop()

window = tk.Tk()
window.title("Main Window")
launchbutton = tk.Button(window,text = "Launch Window",command = lambda: textwindow("Toplevel Popup","Text Area Text"))
launchbutton.pack(padx=20,pady=20)
window.mainloop()

在我的主脚本(和本示例代码)中,单击“全选”按钮将导致以下错误:

AttributeError:“顶级”对象没有属性“ textwidget”

因为我是该语言的新手,我是否缺少一些简单的东西?

编辑:基于Bryan的评论,为清晰起见,修改了第二个示例。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)