I am trying to create a program that displays a portion of a website’s source code. I have written the code that will extract the information from the website but am having trouble getting it into a GUI. I am trying to create it so that a user can enter a URL into a text box, press/click a button, and the portion of the source code is displayed.
Well, you’ll get many opinions of which tools to use, and I do recommend getting your feet wet with others like pygame, but tkinter is built-in already, no need to install anything.
import tkinter as tk
app = tk.Tk()
text_box = tk.Text(app, height=10, width= 50)
text_box.pack()
text_box.insert('end', "Insert your text here")
tk.mainloop()
Example gotten from here:
https://www.python-course.eu/tkinter_text_widget.php
Here is a bit more that may help guide you, the key things to note is:
- A widget takes a parent
- A StringVar uses
textvar=
instead oftext=
when inside of a widget - You can bind buttons, keys, etc
- StringVars, IntVars, DoubleVars, etc updated immediately from the mainloop running
- You can’t pass variables through the command parameter in the button, so we pass an anonymous function, and that function calls your function and brings in a variable from a higher scope
- I used a tuple in the lambda with one element, the comma in the parenthesis tell it that it’s a tuple.
- A widget needs to be created, then placed, in this example I use pack
- A widget does not need to be stored in a variable, but storing it somewhere is a good idea for accessing it later, many prefer to write guis in an object oriented way to help containerize windows, tabs, frames, widgets
- There are plenty of great examples out there, so don’t try to memorize everything, just look up what you need and do a brush up if/when you need to in the future.
- ttk has different styled widgets, you can use either, but ttk is more customizable
import tkinter as tk
from tkinter import ttk
app = tk.Tk()
some_label = ttk.Label(app, text="Enter Url")
some_label.pack()
entrybox_var = tk.StringVar()
entry_box = ttk.Entry(app, textvar=entrybox_var)
entry_box.pack()
entry_button = ttk.Button(app, text="Get Code Now!", command= lambda : (my_function(entrybox_var), ))
entry_button.pack()
def my_function(val):
print(val.get())
app.mainloop()