如何在Tkinter中使用按钮复制到剪贴板?

huangapple go评论58阅读模式
英文:

How to copy to clipboard in Tkinter with button?

问题

我正在开发一个用于生成随机数字的Python/Tkinter程序。

def ButClick():
    try:
        MinNum = int(txt1.get())
        MaxNum = int(txt2.get())
        Num = int(txt3.get())
    except ValueError:
        messagebox.showerror("ValueError", "Check if you typed in correctly! You can't type in text! Numbers only!")
    else:
        Nums = ''
        if MinNum <= MaxNum:
            last = MinNum - 1
            i = 0
            while i < Num:
                numOne = randint(MinNum, MaxNum)
                if numOne != last:
                    Nums = Nums + " " + str(numOne)
                    i += 1
                    last = numOne
            scr.config(state="normal")
            scr.insert(INSERT, str(Nums) + "\n")
            scr.see("end")
            scr.config(state="disabled")
        else:
            messagebox.showerror("NumError!", "Your Min Number can't be higher than your Max Number or vice versa!")

def copy(scr):
    root.clipboard_get(scr)
    root.clipboard_append(scr)

def remove_text():
    scr.config(state="normal")
    scr.delete(1.0, END)
    scr.config(state="disabled")

def confirm():
    answer = askyesno(title='Exit', message='Tired of randomness?')
    if answer:
        root.destroy()

root = Tk()
root.title("Hey")
message = Label(root, text="Welcome to random numbers generator! Developed by Yaroslav Poremsky")
message.pack()

root = Tk()
root.title("Random is so random :)")
# 创建按钮和文本框
lb1 = Label(root, bg="green", text="Min number")
lb1.grid(
    row=0,
    column=0,
    pady=10,
    padx=10)

txt1 = Entry(root, width=30)
txt1.grid(
    row=0,
    column=1,
    pady=10,
    padx=10)

lb2 = Label(root, bg="orange", text="Max number")
lb2.grid(
    row=1,
    column=0,
    pady=10,
    padx=10)

txt2 = Entry(root, width=30)
txt2.grid(
    row=1,
    column=1,
    pady=10,
    padx=10)

lb3 = Label(root, bg="pink", text="Number")
lb3.grid(
    row=2,
    column=0,
    pady=10,
    padx=10)

txt3 = Entry(root, width=30)
txt3.grid(
    row=2,
    column=1,
    pady=10,
    padx=10)

but = Button(root, width=15, height=2, bg="magenta", text="Generate", command=ButClick)
but.grid(
    row=3,
    column=0,
    columnspan=2,  # 可覆盖的相邻列数
    pady=10,
    padx=10)

but_remove = Button(root, width=15, height=2, bg="crimson", text="Remove", command=remove_text)
but_remove.grid(
    row=3,
    column=1,
    columnspan=2,
    pady=15,
    padx=20)

but_quit = Button(root, width=15, height=2, bg="violet", text="Quit", command=confirm)
but_quit.grid(
    row=3,
    column=3,
    columnspan=2,
    pady=15,
    padx=20)

but_copy = Button(root, width=15, height=2, bg="violet", text="Copy", command=copy)
but_copy.grid(
    row=4,
    column=3,
    columnspan=2,
    pady=15,
    padx=20)

scr = scrolledtext.ScrolledText(root, bg="grey", height=10, state="disable")
scr.grid(
    row=4,
    column=0,
    columnspan=2,
    pady=10,
    padx=10)

root.mainloop()

我实现了一个“Copy”按钮,用于将随机生成的数字复制到文本框(scr)中。问题是,我的copy函数返回错误:

return self.func(*args)
TypeError: copy() missing 1 required positional argument: 'scr'

问题可能是什么?

英文:

I'm developing a Python/Tkinter program to generate random numbers.

def ButClick():
try:
MinNum = int (txt1.get())
MaxNum = int (txt2.get())
Num = int (txt3.get())
except ValueError:
messagebox.showerror(&quot;ValueError&quot;, &quot;Check if you typed in correct! You can&#39;t type in text! Numbers only!&quot;)
else:
Nums = &#39;&#39;
if MinNum &lt;= MaxNum: 
last = MinNum - 1  
i = 0
while i &lt; Num:
numOne = randint(MinNum,MaxNum)
if numOne != last:
Nums = Nums + &quot; &quot; + str(numOne)
i += 1              
last = numOne
scr.config(state=&quot;normal&quot;)  
scr.insert(INSERT, str(Nums) + &quot;\n&quot;)
scr.see(&quot;end&quot;)
scr.config(state=&quot;disabled&quot;) 
else:
messagebox.showerror(&quot;NumError!&quot;, &quot;Your Min Number can&#39;t be higher than your Max Number or vice versa!&quot;)
def copy(scr):
root.clipboard_get(scr)
root.clipboard_append(scr)
def remove_text():
scr.config(state=&quot;normal&quot;)
scr.delete(1.0,END)
scr.config(state=&quot;disabled&quot;)
def confirm():
answer = askyesno(title=&#39;Exit&#39;,
message=&#39;Tired of randomness?&#39;)
if answer:
root.destroy() 
root = Tk()
root.title(&quot;Hey&quot;)
message = Label(root, text= &quot;Welcome to random numbers generator! Developed by Yaroslav Poremsky&quot;)
message.pack()
root = Tk()
root.title(&quot;Random is so random :)&quot;)
# Створення кнопок та текстових полів 
lb1 = Label(root, bg = &quot;green&quot;, text = &quot;Min number&quot;) 
lb1.grid(
row = 0, 
column = 0,
pady = 10, 
padx = 10) 
txt1 = Entry(root, width = 30)  
txt1.grid(
row = 0,
column = 1,
pady = 10,
padx = 10)
lb2 = Label(root, bg = &quot;orange&quot;, text = &quot;Max number&quot;)
lb2.grid(
row = 1,
column = 0,
pady = 10,
padx = 10)
txt2 = Entry(root, width = 30)
txt2.grid(
row = 1,
column = 1,
pady = 10,
padx = 10)
lb3 = Label(root,  bg = &quot;pink&quot;, text = &quot;Number&quot;)
lb3.grid(
row = 2,
column = 0,
pady = 10,
padx = 10)
txt3 = Entry(root, width = 30)
txt3.grid(
row = 2,
column = 1,
pady = 10,
padx = 10)
but = Button(root, width = 15, height = 2,  bg = &quot;magenta&quot;, text = &quot;Generate&quot;, command = ButClick) 
but.grid(
row = 3,
column = 0,
columnspan = 2, # кількість суміжних стовпців, які може охоплювати кнопка
pady = 10,
padx = 10)
but_remove = Button(root, width = 15, height = 2, bg = &quot;crimson&quot;, text = &quot;Remove&quot;, command = remove_text) 
but_remove.grid(
row = 3,
column = 1,
columnspan = 2,
pady = 15,
padx = 20)
but_quit = Button(root, width = 15, height = 2, bg = &quot;violet&quot;, text = &quot;Quit&quot;, command = confirm) 
but_quit.grid(
row = 3,
column = 3,
columnspan = 2,
pady = 15,
padx = 20)
but_copy = Button(root, width = 15, height = 2, bg = &quot;violet&quot;, text = &quot;Copy&quot;, command = copy)
but_copy.grid(
row = 4,
column = 3,
columnspan = 2,
pady = 15,
padx = 20)
scr = scrolledtext.ScrolledText(root, bg = &quot;grey&quot;, height = 10, state=&quot;disable&quot;) 
scr.grid(
row = 4,
column = 0,
columnspan = 2,
pady = 10,
padx = 10)
root.mainloop()

I implemented a "Copy" button to copy to clipboard all the randomly generated numbers in the text box(scr). The Problem is, my def copy function returns an error:

  return self.func(*args)
TypeError: copy() missing 1 required positional argument: &#39;scr&#39;

What can be the problem?

答案1

得分: 0

你的 copy 函数以要附加到剪贴板的文本作为参数,但在按下按钮时,你没有向函数传递任何输入(按钮假定输入会隐式传递给它们的函数)。

相反,你可以将你的 copy 函数更改为不带参数,并直接在函数体中读取你的 ScrolledText 部件的值,像这样:

def copy():
    root.clipboard_append(scr.get(1.0, END))
英文:

Your copy function takes as argument the text to be appended to the clipboard, but when pressing the button, you are not passing any input to the function (buttons assume input is given implicitly to their function).

Instead what you can do, is change your copy function to have no arguments, and read the value of your ScrolledText widget directly in the function body, like so:

def copy():
root.clipboard_append(scr.get(1.0, END))

huangapple
  • 本文由 发表于 2023年2月23日 20:02:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定