Home > Blockchain >  How to open a link with an specific button? Tkinter
How to open a link with an specific button? Tkinter

Time:03-16

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()

CodePudding user response:

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