Copying text in tkinter from label or msgbeox - python

I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form

Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets

The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful

Related

Tkinter Entry widget is returning an empty list when used in a toplevel window

I am attempting to open a new window when the New Window button is pressed in the main "root" window. This currently works and does indeed open a second window. In the second window I want to ask the user for an input and then this input will be turned into a list of strings.
An example input would be "Amy, Bob, Carl". The expected output would be ['Amy', 'Bob', 'Carl'] but currently the program just returns [''].
My current code is:
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def open_new_window():
top = Toplevel()
top.title("second window")
entities = Entry(top)
entries = entities.get().split(", ")
entities.pack()
entities.focus_set()
print(entries)
sub_button = Button(top, text="Submit", command= ?)
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
I am new to Tkinter and I am unsure why this is happening. I'm sure it's a simple silly mistake but I can't find where I am going wrong. I also am unsure as to whether I need a Submit button as I don't know what command should be passed to it.
Any advice is appreciated. Please let me know if any additional information is required.
First, we will understand why you got a empty list: your code is executed sequentially, so when you do the entities.get() you haven't yet written anything nor pressed "Submit", i.e., you want to read the entry box once you press the "Submit", not earlier, for that reason, you have the command = ?.
As I am aware, you have mainly 2 options:
Get the text from the button itself
Create a variable linked to the entry box and read this
Method 1: read the data from the entry
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def do_stuff(entry):
print(entry.get())
def open_new_window():
top = Toplevel()
top.title("second window")
entities = Entry(top)
entities.pack()
entities.focus_set()
sub_button = Button(top, text="Submit", command= lambda: do_stuff(entities))
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
Method 2: link a variable
from tkinter import *
root = Tk()
root.title("Welcome screen")
root.geometry("300x300")
def do_stuff(text_entry):
print(text_entry.get())
def open_new_window():
top = Toplevel()
top.title("second window")
text_entry = StringVar()
entities = Entry(top, textvariable = text_entry)
entities.pack()
entities.focus_set()
sub_button = Button(top, text="Submit", command= lambda: do_stuff(text_entry))
sub_button.pack(pady=20)
close_btn = Button(top, text="Close", command=top.destroy)
close_btn.pack()
open_button = Button(root, text="New Window", command=open_new_window)
open_button.pack(pady=20)
exit_button = Button(root, text="Close", command=root.destroy)
exit_button.pack(pady=20)
root.mainloop()
The main advantage in this last approach is that you can play with the text before and after the entry is built.

How can I append elements inputted by user in a tk.Entry object into a list?

I'm trying to build a very simple program in Python and Tkinter that allows the user to input people's names by keyboard and then a button is commanded to select a person from the list at random and show it in a tk.Label object.
My problem is once I run the root.mainloop(), I can add names to the list but the list does not update with the new names.
This is the main code for the Tkinter to initialize
import tkinter as tk
from tkinter import filedialog, Text
import random
root = tk.Tk()
root.title('Millor persona del moment')
root.geometry("500x200")
root.configure(bg='black')
peopleList = []
tk.Label(root, text="Insertar participante: ",fg="#ff007f", bg='black').grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)
addButton = tk.Button(root, text='AƱadir', padx=10, pady=5, fg="#ff007f", bg='black', command=addPerson)
addButton.grid(row=0, column=2)
while peopleList:
turnButton = tk.Button(root, text='Saca Tema', padx=10, pady=5, fg="#ff007f", bg='black', command=wordTurn(peopleList))
turnButton.grid(row=1, column=0)
nom = tk.StringVar()
nom.set('Comencem')
personSpeaking = tk.Label(root, textvariable=nom,fg="#ff007f", bg='black')
personSpeaking.grid(row=1, column=1)
root.mainloop()
And these are the functions I use
def addPerson():
peopleList.append(e1.get())
e1.delete(0,'end')
def wordTurn(peopleList):
person = random.choice(peopleList)
peopleList.remove(person)
nom.set(person)
command=wordTurn(peopleList)) calls the return value of wordTurn when the button is pressed, which is None and should raise an error. Use command=lambda peopleList=peopleList: wordTurn(peopleList)) instead.

I cant get the value from the second textbox in my tkinter application

I'm trying to program a very little app that should start with a window where you put a password, and that works. after that it opens another window and asks for credential that will go into a file (not developed yet!).
My problem is that I can't get the value from the second text widget in the second window. Can someone help me with that?
here's the code:
from tkinter import *
import tkinter as tk
root=Tk()
root.geometry("400x400")
root.title("password test")
def getNewWindow():
root2 = tk.Tk()
root2.geometry("200x200")
root2.title("infos")
textBox2=Text(root2, height=2, width=10)
textBox2.pack()
def retrieve_input2():
inputValue2=textBox2.get("1.0","end-1c")
if inputValue2 == "110604":
pass
buttonCommit=Button(root2, height=1, width=10, text="Commit",
command=lambda: retrieve_input2())
buttonCommit.pack()
def retrieve_input():
inputValue=textBox.get("1.0","end-1c")
if inputValue == "110604":
getNewWindow()
textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit",
command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()
mainloop()

Tkinter not creating a window?

I am trying to create a window with Tkinter but no window is being created and I am not receiving any error codes?
from tkinter import *
def login_window():
window=Tk()
window.title("Login")
info_lbl = Label(window)
info_lbl.grid(row=0, column=1)
username_lbl = Label(window, text='Username')
username_lbl.grid(row=1, column=1)
username_entry = Entry(window, width=10)
username_entry.grid(row=1, column=2)
password_lbl = Label(window, text='Password')
password_lbl.grid(row=2, column=1)
password_entry = Entry(window, width=10, )
password_entry.grid(row=2, column=2)
ok_button = Button(window, text='Login', command = menu_window)
ok_button.grid(row=3,column = 2,sticky =W)
Any help would be great!
Well I think u should add mainloop() inside your function as well as call your login_window something like this-
from Tkinter import *
def login_window():
window=Tk()
window.title("Login")
mainloop()
login_window()
It looks like you never entered the main Tkinter loop. To display that window, you could add this to the bottom of the function:
window.mainloop()
Take a look at this question and the accepted answer for a bit more information on the Tkinter main loop.

How to clear/delete the contents of a Tkinter Text widget?

I am writing a Python program in TKinter on Ubuntu to import and print
the name of files from particular folder in Text widget.
It is just adding filenames to the previous filnames in the Text
widget, but I want to clear it first, then add a fresh list of filenames.
But I am struggling to clear the Text widget's previous list of
filenames.
Can someone please explain how to clear a Text widget?
Screenshoot and coding is giving below:
import os
from Tkinter import *
def viewFile():
path = os.path.expanduser("~/python")
for f in os.listdir(path):
tex.insert(END, f + "\n")
if __name__ == '__main__':
root = Tk()
step= root.attributes('-fullscreen', True)
step = LabelFrame(root, text="FILE MANAGER", font="Arial 20 bold italic")
step.grid(row=0, columnspan=7, sticky='W', padx=100, pady=5, ipadx=130, ipady=25)
Button(step, text="File View", font="Arial 8 bold italic", activebackground=
"turquoise", width=30, height=5, command=viewFile).grid(row=1, column=2)
Button(step, text="Quit", font="Arial 8 bold italic", activebackground=
"turquoise", width=20, height=5, command=root.quit).grid(row=1, column=5)
tex = Text(master=root)
scr=Scrollbar(root, orient=VERTICAL, command=tex.yview)
scr.grid(row=2, column=2, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=2, column=1, sticky=W)
tex.config(yscrollcommand=scr.set, font=('Arial', 8, 'bold', 'italic'))
root.mainloop()
I checked on my side by just adding '1.0' and it start working
tex.delete('1.0', END)
you can also try this
According to the tkinterbook the code to clear a text element should be:
text.delete(1.0,END)
This worked for me. source
It's different from clearing an entry element, which is done like this:
entry.delete(0,END) #note the 0 instead of 1.0
this works
import tkinter as tk
inputEdit.delete("1.0",tk.END)
from Tkinter import *
app = Tk()
# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()
# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()
app.mainloop()
Here's an example of txt.delete(1.0,END) as mentioned.
The use of lambda makes us able to delete the contents without defining an actual function.
for me "1.0" didn't work, but '0' worked. This is Python 2.7.12, just FYI. Also depends on how you import the module. Here's how:
import Tkinter as tk
window = tk.Tk()
textBox = tk.Entry(window)
textBox.pack()
And the following code is called when you need to clear it. In my case there was a button Save that saves the data from the Entry text box and after the button is clicked, the text box is cleared
textBox.delete('0',tk.END)
I think this:
text.delete("1.0", tkinter.END)
Or if you did from tkinter import *
text.delete("1.0", END)
That should work
A lot of answers ask you to use END, but if that's not working for you, try:
text.delete("1.0", "end-1c")
text.delete(0, END)
This deletes everything inside the text box

Categories

Resources