Search code examples
pythontkintertkinter-entry

How do I get custom inputs from entry boxes to form a specific hyperlink?


This is my first time in coding anything and since I have to do this project soon, I couldn't have a proper tutorial in Python.

Here's the thing: I need to program a small window with two entry boxes and a button.

The button needs to add the entries into a pre-determined hyperlink. For example:

Entry 1: 2020 Entry 2: 12345

and when I click the button it should open, let's say, http://www.google.com/2020-12345.html

So far, here's where I'm at:

# !/usr/bin/python3  

from tkinter import *

top = Tk()

import webbrowser

new = 1
url = "http://www.google.com/e1-e2"

def openweb():
    webbrowser.open(url,new=new)

top.geometry("250x100")

name = Label(top, text="Numbers").place(x=50, y=1)

sbmitbtn = Button(top, text="Submit", command=openweb).place(x=90, y=65)

e1 = Entry(top).place(x=20, y=20)
e2 = Entry(top).place(x=20, y=45)

top.mainloop()

Solution

  • Like this:

    from tkinter import *
    import webbrowser
    
    # Use {} as a placeholder to allow format() to fill it in later
    url_template = "http://www.google.com/{}-{}"
    
    def openweb():
        url = url_template.format(e1.get(), e2.get())
        webbrowser.open(url,new=1)
    
    top = Tk()
    top.geometry("250x100")
    
    # Do not use place(). It's very buggy and hard to maintain. Use pack() or grid()
    Label(top, text="Numbers").pack()
    
    # You must use 2 lines for named Widgets. You cannot layout on the same line
    e1 = Entry(top)
    e1.pack()
    e2 = Entry(top)
    e2.pack()
    
    sbmitbtn = Button(top, text="Submit", command=openweb)
    sbmitbtn.pack()
    
    top.mainloop()