Give the ability to user to copy text in tkinter gui - python

In this code when the user enters the link, a short version of the link get displayed but it does not give the ability to the user to copy the link from the GUI. How do i fix this?
import pyshorteners as pr
from tkinter import *
root = Tk()
e = Entry(root, width=50)
e.pack()
def click():
link = e.get()
shortener = pr.Shortener()
Short_Link = shortener.tinyurl.short(link)
Label1 = Label(root, text=Short_Link)
Label1.pack()
Button1 = Button(root, text="Enter link:", command=click)
Button1.pack()
root.mainloop()

You can't directly copy the text from a Tkinter Label widget with CTRL+C.
This is a simple Tkinter app to copy the text of a Label to the clipboard:
from tkinter import *
from tkinter.messagebox import showinfo
class CopyLabel(Tk):
def __init__(self, text: str):
super(CopyLabel, self).__init__()
self.title('Copy this Label')
self.label_text = text
self.label = Label(self, text=text)
self.label.pack(pady=10, padx=40)
self.copy_button = Button(self, text='COPY TO CLIPBOARD', command=self.copy)
self.copy_button.pack(pady=5, padx=40)
def copy(self):
self.clipboard_clear()
self.clipboard_append(self.label_text)
self.update()
showinfo(parent=self, message='Copied to clipboad!')
if __name__ == "__main__":
app = CopyLabel('Copy me!')
app.mainloop()
In your code to copy automatically the Short_Link you can do:
import pyshorteners as pr
from tkinter import *
root = Tk()
e = Entry(root, width=50)
e.pack()
def click(master: Tk):
link = e.get()
shortener = pr.Shortener()
Short_Link = shortener.tinyurl.short(link)
master.clipboard_clear()
master.clipboard_append(Short_Link)
master.update()
Label1 = Label(root, text=Short_Link)
Label1.pack()
Button1 = Button(root, text="Enter link:", command=lambda: click(root))
Button1.pack()
root.mainloop()

Related

Copy a label on tkinter and change the text on button click?

I have some program of this kind of type:
from tkinter import *
def apply_text(lbl_control):
lbl_control['text'] = "This is some test!"
master = Tk()
lbl = Label(master)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
My aim now is to copy the text of the label lbl itself without any ability to change it. I tried the following way to solve the problem:
from tkinter import *
def apply_text(lbl_control):
lbl_control.insert(0, "This is some test!")
master = Tk()
lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
because of state = "readonly" it is not possible to change the text insert of lbl anymore. For that reason nothing happens if I click on the button apply. How can I change it?
There is a simple way to do that simple first change the state of entry to normal, Then insert the text, and then change the state back to readonly.
from tkinter import *
def apply_text(lbl_control):
lbl_control['state'] = 'normal'
lbl_control.delete(0,'end')
lbl_control.insert(0, "This is some test!")
lbl_control['state'] = 'readonly'
master = Tk()
lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
There is another way to do this using textvariable.
Code:(Suggested)
from tkinter import *
def apply_text(lbl_control):
eText.set("This is some test.")
master = Tk()
eText = StringVar()
lbl = Entry(master, state="readonly",textvariable=eText)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()

How to add a button in a topLevel window?

This code is supposed to ask login information from the user. Then when it enters the wrong details, it will do a popup (loginErrorWdw) with a label and a button. The button there will exit the program when pressed.
I'm trying to get the button from loginErrorWdw to appear in that window but it won't. Here's my whole block of code.
from tkinter.ttk import *
from tkinter import messagebox
import tkinter as tk
import sys
import os
class Login(Frame):
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
self.loginWidgets()
def loginWidgets(self):
self.userlbl = Label(self, text="Enter username: ")
self.userlbl.grid()
self.unEntry = Entry(self)
self.unEntry.grid(row=0, column=1, sticky=W)
self.pwlbl = Label(self, text="Enter password: ")
self.pwlbl.grid(row=1, column=0, sticky=W)
self.pwEntry = Entry(self, show="*")
self.pwEntry.grid(row=1, column=1, sticky=W)
self.submitBtn = Button(self, text="LOGIN", command=self.checkLogin)
self.submitBtn.grid(row=2, column=1, sticky=W)
def loginErrorWdw(self):
err = tk.Toplevel(self)
err.title("Error")
l = tk.Label(err, text="Invalid login details! The program will exit.")
l.pack(side="top", expand=False, padx=20, pady=20)
btn=tk.Button(err, text="Ok", command=self.exitBtn)
def exitBtn(self):
os._exit(0)
#change def position
def mainWdw(self):
messagebox.showinfo('Main window','Message pop up')
def checkLogin(self):
user = self.unEntry.get()
pw = self.pwEntry.get()
if user == "admin":
if pw == "lbymf1d":
self.mainWdw()
else:
self.loginErrorWdw()
else:
self.loginErrorWdw()
# un = admin, pw = lbymf1d
#window = var
window = Tk()
window.title("Login UI")
# window size
window.geometry('700x300')
login = Login(window)
# loop for window
window.mainloop()
You forgot about btn.pack()
This is way without errors:
from tkinter.ttk import *
from tkinter import messagebox
import tkinter as tk
import sys
# import os
class Login(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.loginWidgets()
def loginWidgets(self):
self.userlbl = Label(self, text="Enter username: ")
self.userlbl.grid()
self.unEntry = Entry(self)
self.unEntry.grid(row=0, column=1, sticky="W") # sticky must be string
self.pwlbl = Label(self, text="Enter password: ")
self.pwlbl.grid(row=1, column=0, sticky="W")
self.pwEntry = Entry(self, show="*")
self.pwEntry.grid(row=1, column=1, sticky="W")
self.submitBtn = Button(self, text="LOGIN", command=self.checkLogin)
self.submitBtn.grid(row=2, column=1, sticky="W")
def loginErrorWdw(self):
err = tk.Toplevel(self)
err.title("Error")
l = tk.Label(err, text="Invalid login details! The program will exit.")
l.pack(side="top", expand=False, padx=20, pady=20)
btn = tk.Button(err, text="Ok", command=self.exitBtn)
btn.pack() # Draw it
def exitBtn(self):
sys.exit(0) # Exit
# change def position
def mainWdw(self):
messagebox.showinfo('Main window', 'Message pop up')
def checkLogin(self):
user = self.unEntry.get()
pw = self.pwEntry.get()
if user == "admin":
if pw == "lbymf1d":
self.mainWdw()
else:
self.loginErrorWdw()
else:
self.loginErrorWdw()
# un = admin, pw = lbymf1d
# window = var
window = tk.Tk()
window.title("Login UI")
# window size
window.geometry('700x300')
login = Login(window)
# loop for window
window.mainloop()

Tkinter Button does nothing when clicked

This is the code for my personal project, for some reason, I can't get the button to do anything when pressed.
Edit: So I managed to fix the text deleting after each input, so now it will continue to output as many passwords as I want. I removed the 0.0 in output.delete so it doesn't default the text to 0 after each generated password.
from tkinter import *
from datetime import datetime
import pyperclip as pc
def close_window():
window.destroy()
exit()
# Main GUI program
window = Tk()
window.frame()
window.grid_rowconfigure((0, 1), weight=1)
window.grid_columnconfigure((0, 1), weight=1)
window.title("PW Gen")
window.geometry('+10+10')
window.configure(background="black")
Label(window, bg="black", height=0, width=25, font="Raleway").grid(row=1, column=0, sticky=NSEW)
# Enter the last 4 and generate the password
Label(window, text="Enter the last 4 digits of the Reader Name:", bg="black", fg="white", font="Raleway 12 bold").grid(row=1, column=0, sticky=W)
textentry = Entry(window, width=53, bg="white")
textentry.grid(row=2, column=0, sticky=W)
Button(window, text="Generate Password", width=16, font="Raleway 8 bold", command=click).grid(row=3, column=0, sticky=W)
# Output the password
Label(window, text="\nPassword", bg="black", fg="white", font="Raleway 12 bold").grid(row=4, column=0, sticky=W)
output = Text(window, width=40, height=4, wrap=WORD, background="white")
output.grid(row=5, column=0, columnspan=2, sticky=W)
# Button and Text To Quit GUI
Label(window, text="Click to Quit", bg="black", fg="white", font="Raleway 12 bold").grid(row=6, column=0, sticky=W)
Button(window, text="Quit", width=14, font="Raleway 8 bold", command=close_window).grid(row=7, column=0, sticky=W)
window.mainloop()
Not exactly the best solution but you can definitely give it a try.
import tkinter as tk
from datetime import datetime
import string
import pyperclip as pc
import random
root = tk.Tk()
root.title("PW Gen")
root.geometry('+10+10')
mainframe = tk.Frame(root)
text = tk.Text(root, height=5, width=25, font="Raleway")
def pwgen():
last4=text.get('1.0','end')[-5:]
j=[char for char in last4 if char in string.ascii_uppercase or char in string.ascii_lowercase]
print(j)
random.shuffle(j)
print(j)
today = datetime.today()
pw = int(today.strftime("%d")) * int(today.strftime("%m"))
last4=''.join(j)
pwgen = "$ynEL" + str(pw) + str()
pc.copy(pwgen)
print("\nThe password is $ynEL" + str(pw) + str(last4))
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.quit1 = tk.Button(self, text="QUIT", fg="black", command=self.master.destroy)
self.quit1.pack(side="top")
text.pack(side="bottom")
self.b2 = tk.Button(self)
self.create_widgets()
self.pack()
def create_widgets(self):
self.b2["text"] = "GenPW"
self.b2["command"] = pwgen
self.b2.pack(side="left")
def b1(self):
self.b2 = tk.Button(self, text="Generate PW", command=pwgen)
app = Application(root)
root.mainloop()
The code has many problems.
mainframe is not shown and never used.
Text is shown, but never used.
Text is packed inside Application but is not part of Application.
pwgen uses input and no GUI widget. A infinte loop with a GUI application is not good.
You should use the attributes of a datetime directly.
You should not generate the password at two places in the code.
You should not name a local variable like the function.
In Application you are using b1 as method, this method is overloaded by the attribute b1, so you cannot use the method anymore.
In the method b1 you are generating a new butten instead of calling the function pwgen.
import tkinter as tk
from datetime import datetime
import pyperclip as pc
def pwgen():
today = datetime.today()
pw = today.day * today.month
last4 = input("Last 4 of Reader Name [****] ")
password = f"$ynEL{pw}{last4}"
pc.copy(password)
print("\nThe password is", password)
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.quit = tk.Button(self, text="QUIT", fg="black", command=self.master.destroy)
self.quit.pack(side="top")
self.b1 = tk.Button(self, text="GenPW", command=self.click_b1)
self.b1.pack(side="left")
def click_b1(self):
pwgen()
def main():
root = tk.Tk()
root.title("PW Gen")
root.geometry('+10+10')
text = tk.Text(root, height=5, width=25, font="Raleway")
text.pack(side="bottom")
app = Application(master=root)
app.pack()
root.mainloop()
if __name__ == "__main__":
main()
This works. I have used grid manager for more control and removed unused code.
import tkinter as tk
from tkinter import *
from datetime import datetime
import pyperclip as pc
root = tk.Tk()
root.title("PW Gen")
root.geometry('+10+10')
Text = tk.Text(root, height=5, width=25, font="Raleway")
def pwgen():
while True:
today = datetime.today()
pw = int(today.strftime("%d")) * int(today.strftime("%m"))
last4 = input("Last 4 of Reader Name [****] ")
pwgen = "$ynEL" + str(pw) + str(last4)
pc.copy(pwgen)
print("\nThe password is $ynEL" + str(pw) + str(last4))
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.quit = tk.Button(self, text="QUIT", fg="black", command=self.master.destroy)
self.quit.grid(row=0,column=0,sticky=tk.EW)
Text.grid(row=1,column=0,sticky=tk.NSEW)
self.b1 = tk.Button(self, text="Generate PW", command=pwgen)
self.b1.grid(row=0,column=1,sticky=tk.EW)
self.grid(row=0,column=0,sticky=tk.NSEW)
app = Application(master=root)
root.mainloop()
A previous version created multiple Generate PW buttons.

Python Tkinter doesn't show the label when I press the button

I have one Input and one button. I want the value of the input (Entry) to when I press the button. When I type print(mtext) it works well, but when I put it in a Label it doesn't work.
Here is the code:
from tkinter import *
root = Tk()
root.title("Mohamed Atef")
root.geometry("900x600")
var = StringVar()
var.set("Please write something")
label = Label(root, textvariable=var, padx=10, pady=10)
#input
text = StringVar()
entry = Entry(root, textvariable=text)
def mohamed():
mtext = text.get()
mohamed = Label(root, textvariable=mtext)
mohamed.pack()
#button
buttonText = StringVar()
buttonText.set("Click me !")
button = Button(root, textvariable=buttonText, command=mohamed)
label.pack()
entry.pack()
button.pack()
root.mainloop()
Same as Flilp, your finished product would look like this
from tkinter import *
root = Tk()
root.title("Mohamed Atef")
root.geometry("900x600")
var = StringVar()
var.set("Please write something")
label = Label(root, textvariable=var, padx=10, pady=10)
#input
text = StringVar()
entry = Entry(root, textvariable=text)
def mohamed() :
mtext = text.get()
mohamed = Label(root, text=mtext)
mohamed.pack()
#button
buttonText = StringVar()
buttonText.set("Click me !")
button = Button(root, textvariable=buttonText, command=mohamed)
label.pack()
entry.pack()
button.pack()
root.mainloop()
If you just want text that's in your Entry to appear under your labels you could do:
def mohamed():
mohamed = Label(root, textvariable=text)
mohamed.pack()
Your code didn't work because value passed as textvariable should be tkinter StringVar() not string.
If you don't want the text to be constantly updated when you change your Entry you should do:
def mohamed():
mtext = text.get()
mohamed = Label(root, text=mtext)
mohamed.pack()

Tkinter new window

I'm relatively new to Tkinter and I need help.
I have created a new window when a button is clicked from the parent window. The new window is the def new_Window. But I can't seem to get the information in the window as coded below:
from tkinter import *
from tkinter import ttk
#User Interface Code
root = Tk() #Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel(root)
display = Label(newWindow, width=200, height=50)
message = Label(root, text="Welcome")
display.pack()
message.pack()
display2 = Label(root, width=100, height=30)
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
message_label = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
username = StringVar() #Stores the username in text
user_entry = Entry(root, textvariable=username) #Creates an entry for the
username
user_entry.pack()
display2.pack()
button1.pack()
message_label.pack()
root.mainloop()#Runs the main window loop
Thanks for your help.
You did not pack the hello label into the new window. A tip is also to use background colors to visualize labels when developing. Here is a functioning code for you. I only changed 2 lines, added foreground and background.
from tkinter import *
from tkinter import ttk
# User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel(root)
display = Label(newWindow, width=200, height=50,bg='RED')
message = Label(newWindow, text="HEEEY",fg='BLACK',bg='GREEN')
message.pack()
display.pack()
display2 = Label(root, width=100, height=30)
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
message_label = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
username = StringVar() # Stores the username in text
user_entry = Entry(root, textvariable=username) # Creates an entry for the
username
user_entry.pack()
display2.pack()
button1.pack()
message_label.pack()
root.mainloop() # Runs the main window loop

Categories