How to open a link with an specific button? Tkinter - python

Basically, when I want to open a specific link with a specific button it won't work. When you click the second button, it opens all the links inside the function.
from tkinter import *
import webbrowser
root = Tk()
root.title("links")
root.geometry("700x500")
root.config(bg="#3062C7")
def links_unit1():
global vid_1, vid_2
bg_v1 = Canvas(root, bg="#3062C7", width=700, height=500)
bg_v1.place(x=0, y=0)
vid_1 = Button(root, text="Virtual memory", command=all_vids1)
vid_1.place(x=20, y=20)
vid_2 = Button(root, text="lossy, lossless", command=all_vids1)
vid_2.place(x=30, y=50)
def all_vids1():
if vid_1:
webbrowser.open("https://youtu.be/AMj4A1EBTTY")
elif vid_2:
webbrowser.open("https://youtu.be/v1u-vY6NEmM")
vid_unit1 = Button(root, text="Unit 1", command=links_unit1)
vid_unit1.place(x=10, y=10)
root.mainloop()

You can't do it by checking the values of vid_1 and vid_2 because they will always be truthy. Instead you can create to anonymous function "on-the-fly" by using a lambda expression for the command= option of the Button as shown below:
from tkinter import *
import webbrowser
root = Tk()
root.title("links")
root.geometry("700x500")
root.config(bg="#3062C7")
def links_unit1():
bg_v1 = Canvas(root, bg="#3062C7", width=700, height=500)
bg_v1.place(x=0, y=0)
vid_1 = Button(root, text="Virtual memory",
command=lambda: webbrowser.open("https://youtu.be/AMj4A1EBTTY"))
vid_1.place(x=20, y=20)
vid_2 = Button(root, text="Lossy, Lossless",
command=lambda: webbrowser.open("https://youtu.be/v1u-vY6NEmM"))
vid_2.place(x=30, y=50)
vid_unit1 = Button(root, text="Unit 1", command=links_unit1)
vid_unit1.place(x=10, y=10)
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 seperate Tkinter Gui app source code into multiple files

i'm working on downloading manager python gui app using Tkinter and halfway there my code started to look very messy so i decided to seperate functions on different file and then import it:
my main code:
from tkinter import *
from functions import add_download
root = Tk()
root.title("The Pownloader!")
canvas = Canvas(root, width=700, height=500).pack()
# Buttons:
ADD_BUTTON = Button(root, text="ADD", bd=4, height=2, width=5, command=add_download)
SETTINGS_BUTTON = Button(root, text="SETTINGS", bd=4, height=2, width=5)
ABOUT_BUTTON = Button(root, text="ABOUT", bd=4, height=2, width=5)
EXIT_BUTTON = Button(root, text="EXIT", bd=4, height=2, width=5, command=quit)
# Mini-Buttons:
PAUSE_MINI_BUTTON = Button(root, text="PAUSE", font=(None, "8"), height=2, width=3)
RESUME_MINI_BUTTON = Button(root, text="RESUME", font=(None, "8"), height=2, width=3)
REMOVE_MINI_BUTTON = Button(root, text="REMOVE", font=(None, "8"), height=2, width=3)
# Side_Mini_Buttons:
DOWNLOAD_WINDOW = Button(root, text="Downloads", font=(None, "8"), height=3, width=6)
ERRORS_WINDOW = Button(root, text="Failed", font=(None, "8"), height=3, width=6)
COMPLETED_WINDOW = Button(root, text="Completed", font=(None, "8"), height=3, width=6)
# Positionning Buttons:
ADD_BUTTON.place(x=70, y=20)
SETTINGS_BUTTON.place(x=145, y=20)
ABOUT_BUTTON.place(x=220, y=20)
EXIT_BUTTON.place(x=295, y=20)
PAUSE_MINI_BUTTON.place(x=290, y=455)
RESUME_MINI_BUTTON.place(x=340, y=455)
REMOVE_MINI_BUTTON.place(x=390, y=455)
DOWNLOAD_WINDOW.place(x=1, y=100)
ERRORS_WINDOW.place(x=1, y=160)
COMPLETED_WINDOW.place(x=1, y=220)
# Download Frame:
DOWNLOAD_LIST_LABEL = Label(root, text="Download List:")
DOWNLOAD_LIST_LABEL.place(x=70, y=80)
DOWNLOAD_ENTRIES = Listbox(root, width=70, height=19)
DOWNLOAD_ENTRIES.place(x=70, y=100)
# Main Loop:
root.mainloop()
However my functions.py code looks like this:
def add_download():
# Defining The Pop-up frame:
top = Toplevel(root, width = 420, height = 150)
top.title("New Download")
# Putting on widgets:
link = StringVar()
LINK_LABEL = Label(top, text = "Paste Link:")
FIELD_ENTRY = Entry(top, width = 40, textvariable=link)
def on_click():
link_to_verify = (link.get()).strip()
if len(link_to_verify)>15:
if link_to_verify[0:11]=="http://www.":
DOWNLOAD_ENTRIES.insert(0, link_to_verify)
else:
print("Stupid")
else:
print("not a valid link")
BUTTONS_WIDGET = Frame(top)
ADD_BUTTON = Button(BUTTONS_WIDGET, text = "Add", width=10, command=on_click)
CANCEL_BUTTON = Button(BUTTONS_WIDGET, text = "Cancel", width=10, command=top.destroy)
# Positionning everythig:
LINK_LABEL.grid(column=0,row=0)
FIELD_ENTRY.grid(column=1,row=0)
BUTTONS_WIDGET.grid(column=1,row=2)
ADD_BUTTON.grid(column=0,row=0)
CANCEL_BUTTON.grid(column=1,row=0)
basically i wanted the function to call and show a pop-up window, i'm sure this could done in a million times better but i'm just learning, however i receive an error says:
Toplevel is not defined
Every file needs to import tkinter.
In addition, any variables in the main file which are needed by the imported functions need to be passed into the functions. For example, you should define add_download to accept the root window as a parameter.
def add_download(root):
...
Then, in the main program, pass root as that parameter:
ADD_BUTTON = Button(root, ..., command=lambda: add_download(root))
You will need to build a class to manage it.
Inside run.py:
import tkinter as tk
from interface import GUI
root = tk.Tk()
GUI(root)
Then inside your interface.py script you can call in additional modules:
import tkinter as tk
from aux import AuxGUI
from menu import MenuGUI
class GUI:
def __init__(self, master):
self.master = master
self.GUI_list = []
self.AuxGUI = AuxGUI(self.master, self.GUI_list) # Additional module
self.MenuGUI = MenuGUI (self.master, self.GUI_list) # Additional module
Then you can use OOP to access functions or objects to dynamically interact with each other.
self.GUI_list.append(self.AuxGUI)
self.GUI_list.append(self.MenuGUI)
Inside menu.py identify the correct index from the GUI_list:
import tkinter as tk
class MenuGUI:
def __init__(self, master, GUI_list):
self.master = master
self.AuxGUI = GUI_list[0]

How do I make my button know what`s in the entry box and then print that value in a new window?

I want after you write something in the entry box and then you press the button a new window to pop up and
the number that was written in the entry box to be printed in the new window as " Your height is: "value" but after many tries I still don`t understand how to do it.
my code:
import tkinter as tk
root = tk.Tk()
root.geometry("250x130")
root.resizable(False, False)
lbl = tk.Label(root, text="Input your height", font="Segoe, 11").place(x=8, y=52)
entry = tk.Entry(root,width=15).place(x=130, y=55)
btn1 = tk.Button(root, text="Enter", width=12, height=1).place(x=130, y=85) #command=entrytxt1
root.mainloop()
This is what I got:
import tkinter as tk
root = tk.Tk()
root.resizable(False, False)
def callback():
# Create a new window
new_window = tk.Toplevel()
new_window.resizable(False, False)
# `entry.get()` gets the user input
new_window_lbl = tk.Label(new_window, text="You chose: "+entry.get())
new_window_lbl.pack()
# `new_window.destroy` destroys the new window
new_window_btn = tk.Button(new_window, text="Close", command=new_window.destroy)
new_window_btn.pack()
lbl = tk.Label(root, text="Input your height", font="Segoe, 11")
lbl.grid(row=1, column=1)
entry = tk.Entry(root, width=15)
entry.grid(row=1, column=2)
btn1 = tk.Button(root, text="Enter", command=callback)
btn1.grid(row=1, column=3)
root.mainloop()
Basically when the button is clicked it calls the function named callback. It creates a new window, gets the user's input (entry.get()) and puts it in a label.

How do I use Tkinter buttons to open webrowsers properly?

Everything looks right, but when I run the program the buttons and the websites open at the same time and then the buttons don't work?
import webbrowser
from tkinter import *
from tkinter import ttk
root = Tk()
style = ttk.Style()
open_facebook = webbrowser.open('http://www.facebook.com')
open_google = webbrowser.open('http://www.google.com')
open_yahoo = webbrowser.open('http://www.yahoo.com')
open_youtube = webbrowser.open('http://www.youtube.com')
style.configure("TButton",
font="Serif 18",
padding=10)
main_frame = Frame(root)
main_frame.grid(row=0, columnspan=4)
button_facebook = ttk.Button(main_frame, text='Facebook', command=open_facebook).grid(row=1, column=0)
button_google = ttk.Button(main_frame, text='Google', command=open_google).grid(row=1, column=1)
button_yahoo = ttk.Button(main_frame, text='Yahoo', command=open_yahoo).grid(row=1, column=2)
button_youtube = ttk.Button(main_frame, text='Youtube', command=open_youtube).grid(row=1, column=3)
root.mainloop()
I couldn't manage to make it work with the code you had presented, but I could make it work using lambda in the command portion of the button. This was the only way I could ensure that the web browser didn't open the sites until the buttons were pressed.
import webbrowser
from tkinter import *
from tkinter import ttk
root = Tk()
style = ttk.Style()
style.configure("TButton",
font="Serif 18",
padding=10)
main_frame = Frame(root)
main_frame.grid(row=0, columnspan=4)
button_facebook = ttk.Button(main_frame, text='Facebook', command= lambda:
webbrowser.open('http://www.facebook.com'))
button_google = ttk.Button(main_frame, text='Google', command= lambda:
webbrowser.open('http://www.google.com'))
button_yahoo = ttk.Button(main_frame, text='Yahoo', command= lambda:
webbrowser.open('http://www.yahoo.com'))
button_youtube = ttk.Button(main_frame, text='Youtube', command= lambda:
webbrowser.open('http://www.youtube.com'))
button_facebook.grid(row=1, column=0)
button_google.grid(row=1, column=1)
button_yahoo.grid(row=1, column=2)
button_youtube.grid(row=1, column=3)
root.mainloop()

Is using if statements possible with Tkinter Buttons

What I would like to occur is that when I press the other button, the first label is destroyed and only the corresponding label is on the GUI. Is there a way to incorporate If statements into this or should I approach it another way?
from tkinter import *
root = Tk()
root.geometry("250x50")
def func1():
label = Label(root, text = 'Hello', fg="White", bg="Orange" )
label.pack(fill=BOTH, expand=True)
def func2():
label = Label(root, text = 'Goodbye', fg="White", bg="Orange" )
label.pack(fill=BOTH, expand=True)
button1 = Button(root, text = "Button 1", command = func1, fg="White",
bg="Black", width=10, height=5)
button1.pack(side=LEFT)
button2 = Button(root, text = "Button 2", command = func2, fg="White",
bg="Black", width=10, height=5)
button2.pack(side=LEFT)
root.mainloop()
Here is the approach that #jasonsharper proposed: It is indeed easier to have a single Label, created at the start, then to use the two buttons to set its text, and other properties.
import tkinter as tk
if __name__ == '__main__':
root = tk.Tk()
root.geometry("250x50")
def set_label(txt):
label['text'] = txt
label['fg'] = "White"
label['bg'] = "Orange"
button1 = tk.Button(root, text = "Button 1", command = lambda x='hello': set_label(x), fg="White", bg="Black", width=10, height=5)
button1.pack(side=tk.LEFT)
button2 = tk.Button(root, text = "Button 2", command = lambda x='bye': set_label(x), fg="White", bg="Black", width=10, height=5)
button2.pack(side=tk.LEFT)
label = tk.Label(root, text='')
label.pack(fill=tk.BOTH, expand=True)
root.mainloop()
Note:
Please avoid import * --> to keep your namespace clean, use import tkinter as tk

Categories