how to upgrade the widget, to enter more information - python-3.x

There is code that checks the availability of sites, but it does it for one url, how can I make it so that I can insert an unlimited number of links in the widget, and each of these links will be checked
import requests
import time
import tkinter
from tkinter import *
from tkinter import messagebox
def SiteCheck():
Site_Value=GetSiteBox.get("1.0","end-1c")
Get_Response = requests.get(Site_Value)
if Get_Response != 200:
messagebox.showerror(title = 'Will It Works ?', message = f"The website \"{Site_Value}\" doesn't works ")
else :
messagebox.showinfo(title="OH NO !", message= f"The website \"{Site_Value}\" works! ")
time.sleep(0.4)
window = Tk()
window.title("SiteChecker")
window.geometry('400x300')
MainFrame = Frame(
window,
padx = 10,
pady = 10
)
MainFrame.pack(expand=True)
weight_lb = Label(
MainFrame,
text="Insert links "
)
weight_lb.grid(row=3, column=1)
GetSiteBox = Text(
MainFrame,
height=1,
width= 20
)
GetSiteBox.grid(row=3, column=3)
Check_Button = Button(
MainFrame,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=4, column=3)
window.mainloop()

Related

What needs to be redone to make the code read the entered information

how the "def" function should be redone
to read the urls entered by the user from the interface, and check for availability with output
I tried to do it, but it didn't work, I don't understand how to do it right
import requests
import time
import tkinter
from tkinter import *
from tkinter import messagebox
from sys import argv
def SiteChek():
sylk = weight_tf.get()
for url in sylk:
response = requests.get(url)
if response.status_code != 200:
messagebox.showinfo(f"{url = }")
messagebox.showinfo(f"{response.status_code = }")
time.sleep(0.4)
window = Tk()
window.title("SiteChecker")
window.geometry('400x300')
frame = Frame(
window,
padx = 10,
pady = 10
)
frame.pack(expand=True)
weight_lb = Label(
frame,
text="Insert links "
)
weight_lb.grid(row=3, column=1)
weight_tf = Entry(
frame,
)
weight_tf.grid(row=3, column=3)
cal_btn = Button(
frame,
command = SiteChek,
text='Start checking',
)
cal_btn.grid(row=4, column=3)
window.mainloop()
there is how to do it :
def SiteCheck():
Site_Value=GetSiteBox.get("1.0","end-1c")
Get_Response = requests.get(Site_Value)
if Get_Response != 200:
messagebox.showinfo(title = 'Will It Works ?', message = f"The website \"{Site_Value}\" works ! ")
else :
messagebox.showerror(title="OH NO !", message= f"The website \"{Site_Value}\" doesn't works ")
time.sleep(0.4)
GetSiteBox.get("1.0","end-1c") retrieves all the text entered into the GetSiteBox widget, from the beginning of the text to the end of the text, minus the last newline character. It uses the get() method of the Text widget, which takes two arguments for the starting and ending index of the text to retrieve.
As well as the messagebox that i modified because u needed to write title= and for the message part message=.
As for this part :
MainFrame = Frame(
window,
padx = 10,
pady = 10
)
MainFrame.pack(expand=True)
weight_lb = Label(
MainFrame,
text="Insert links "
)
weight_lb.grid(row=3, column=1)
GetSiteBox = Text(
MainFrame,
height=1,
width= 20
)
GetSiteBox.grid(row=3, column=3)
Check_Button = Button(
MainFrame,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=4, column=3)
window.mainloop()
I just made GetSiteBox a Text Widget to make it easier and made some GUI modificiation because of the Text Widget and I also changed the names of the variables so it will be more easy for you if you want to make a bigger project.
Sorry for poor explanation and bad english, I hope this helped !

How to configure time.spleep correctly

I wrote the code, and need to display notifications at a user-specified time, but for some reason notifications are not displayed at the specified time, what's wrong?
I also tried to assign an int value to a variable, but alas, in this case an error was thrown
from tkinter import ttk
from tkinter import scrolledtext
import requests
import time
from tkinter import *
from tkinter import messagebox
def SiteCheck():
Site_Value = GetSiteBox.get("1.0", "end-1c")
Get_Response = requests.get(Site_Value)
if Get_Response.status_code != 200:
messagebox.showerror(title='Error', message=f"The website \"{Site_Value}\" dont work ")
else:
messagebox.showinfo(title="Successfully", message=f"The website \"{Site_Value}\" work")
time.sleep(TimeCh)
root = tk.Tk()
root.title("SITE CHECKER")
root.geometry('500x300')
ttk.Label(root, text="Enter link to verify",
font=("Times New Roman", 15)).grid(column=0, row=0)
GetSiteBox = scrolledtext.ScrolledText(root, wrap=tk.WORD,
width=57, height=11,
font=("Times New Roman", 12))
GetSiteBox.grid(column=0, row=2, pady=10, padx=10)
Check_Button = Button(
root,
command = SiteCheck,
text='Start checking',
)
Check_Button.grid(row=3, column=0)
TimeCheck = Entry(root,width=10)
TimeCheck.grid(column=0, row=1)
TimeCh = TimeCheck.get()
GetSiteBox.focus()
root.mainloop()

python 3+ with tkinter: modal window not appearing

I'm new to python. I'm trying to set up a GUI with a main window and a modal window to receive the database credentials. The main window has to be in the background when the modal window appears and the user should not interact with it. Actually the application should terminate in case the user fails to provide a valid username and password. I'm presenting part of the code here. What I get is the main window (the modal window does not appear at all) and I can't do anything but shut the program down - not directly; only through visual studio.
'''
import tkinter as tk
class login:
def checkDbCredentials(self, user, password):
if (len(user)<4 or len(password)<4):
return 0
return 1
def ok(self):
us = self.user.get()
pw = self.password.get()
if self.checkDbCredentials(us, pw)==0:
tk.messagebox.showinfo("Error", "Username and Password do not match")
sys.exit(0)
self.dic['user']=us
self.dic['pass']=pw
self.win2.destroy()
def cancel(self, event=None):
self.parent.focus_set()
self.destroy()
def widgets(self):
x = self.win2.winfo_screenwidth()
y = self.win2.winfo_screenheight()
xx = int((x-270)/2)
yy = int((y-85)/2)
geo = "270x85+" + str(xx) + "+" + str(yy)
self.win2.geometry(newGeometry=geo)
self.tempLab= tk.Label(self.win2, text="Username:", pady=5)
self.tempLab1 = tk.Label(self.win2, text="Password:")
self.iuser = tk.Entry(self.win2, textvariable = self.user, width=30)
self.ipass = tk.Entry(self.win2, textvariable = self.password, width=30, show="*")
self.tempLab.grid(column=0, row=0)
self.tempLab1.grid(column=0, row=1)
self.iuser.grid(column=1, row=0)
self.ipass.grid(column=1, row=1)
self.bt = tk.Button(self.win2, text="Submit", command=lambda: self.ok())
self.bt.grid(column=0, row=2, columnspan=2, pady=5)
self.win2.bind("<Return>", self.ok)
self.win2.bind("<Escape>", self.cancel)
def __init__(self, dic, parent):
self.win2 = tk.Toplevel(parent)
self.parent=parent
self.dic = dic
self.user = tk.StringVar()
self.password = tk.StringVar()
self.win2.overrideredirect(1)
self.widgets()
self.win2.transient(parent)
self.win2.grab_set()
self.win2.protocol("WM_DELETE_WINDOW", self.cancel)
self.parent.wait_window(self.win2)
And the main class code is the following:
import tkinter as tk
from tkinter import ttk, X, Y, BOTH
from tkinter import messagebox
import sys
import login
class mainWindow:
def connect(bt, fr):
notImplementedYet()
def notImplementedYet():
msg = tk.messagebox
msg.showinfo("Warning", "Not Implemented yet!")
btX = 20
btY = 5
btSunken = '#aec2c2' # sunken button color
btRaised = '#85adad' # normal button color
rw = 0 # starting row for buttons
cl = 0 # starting column
dbCredentials = {"user":"", "pass":""}
win = tk.Tk()
win.title("Title")
win.geometry(newGeometry="1366x700+00+00")
win.iconbitmap(bitmap="bitmap.ico")
fr1 = tk.Frame(win, width=1366, height=50, background='beige')
fr1.grid(column=cl, row=rw, rowspan=5)
fr2 = tk.Frame(win)
fr2.grid(column=0, row=1)
lb2 = tk.Label(fr2, text="frame 2", background=btRaised)
btConnect = tk.Button(fr1, text="Connect", background = btRaised ,command=lambda: connect(btConnect, fr1), width=btX, height=btY)
btConnect.grid(column=0, row=0)
log = login.login(dbCredentials, win)
win.wait_window(log.win2)
print(dbCredentials)
win.mainloop()
win = mainWindow()
The question is why is the modal window not appearing? I've tried placing the 'wait_window' in the other class as well but it's still not working.

How to make Tkinter button open in the same windows like in many other programs

I have a program calculator, the button code opens a new window, but I want the button calculator run in the same window but not two separate, how do I instead run my code in the same windows?
P.S. the code is not mine, it is as an example
from tkinter import *
root = Tk()
root.title("Math Lab")
root.geometry("1400x1000")
heading = Label(root, text = "Welcome to the MATH Lab", font=("Berlin Sans FB", 40, "bold"), fg= "steelblue").pack()
root.configure(background= "powder blue")
def calculator():
w = Tk()
w.geometry("1400x1000")
def evaluate1():
res.configure(text="Answer: " + str(eval(entry.get())))
def evaluate(event):
res.configure(text="Answer: " + str(eval(entry.get())))
but1 = Button(w, text="Enter", width=10, height=3)
but1.place(x=650, y=100)
but1.config(command=evaluate1)
Label(w, text="Your Expression:").pack()
entry = Entry(w)
entry.bind("<Return>", evaluate)
entry.pack()
res = Label(w)
res.pack()
w.mainloop()
but1=Button(root,text="Calculator",width = 10, height = 3)
but1.place(x=100, y=100)
but1.config(command = calculator)
root.mainloop()
Any suggestions?
Here you are requesting a new window:
w = Tk()
Replace it with
w = root
and you are good to go.
(Well, you'll want to tidy up some x,y offsets, for aesthetics.)

How to show images from path in new window in python tk

After browsing path of image i wanna show image on next window in python using Tk library but image is not showing in next window. please take a look on my code below and give answer Thanks.
import tkinter as tk
from tkinter import filedialog as fd
a=""
str1 = "e"
class Browse(tk.Frame):
""" Creates a frame that contains a button when clicked lets the user to select
a file and put its filepath into an entry.
"""
def __init__(self, master, initialdir='', filetypes=()):
super().__init__(master)
self.filepath = tk.StringVar()
self._initaldir = initialdir
self._filetypes = filetypes
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
a=self._entry
self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))
def _display_widgets(self):
self._label.pack(fill='y')
self._entry.pack(fill='x', expand=True)
self._button.pack(fill='y')
self._classify.pack(fill='y')
def retrieve_input(self):
#str1 = self._entry.get()
#a=a.replace('/','//')
print (str1)
def classify(self):
newwin = tk.Toplevel(root)
newwin.geometry("500x500")
label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
label.pack()
canvas = tk.Canvas(newwin, height=300, width=300)
canvas.pack()
my_image = tk.PhotoImage(file=a, master=root)
canvas.create_image(150, 150, image=my_image)
newwin.mainloop()
def browse(self):
""" Browses a .png file or all files and then puts it on the entry.
"""
self.filepath.set(fd.askopenfilename(initialdir=self._initaldir,
filetypes=self._filetypes))
if __name__ == '__main__':
root = tk.Tk()
labelfont = ('times', 10, 'bold')
root.geometry("500x500")
filetypes = (
('Portable Network Graphics', '*.png'),
("All files", "*.*")
)
file_browser = Browse(root, initialdir=r"C:\Users",
filetypes=filetypes)
file_browser.pack(fill='y')
root.mainloop()
Your global variable a which stores the path of the image is not getting updated. You need to explicitly do it. Below is the code that works. Have a look at the browse() function.
import tkinter as tk
from tkinter import filedialog as fd
a=""
str1 = "e"
class Browse(tk.Frame):
""" Creates a frame that contains a button when clicked lets the user to select
a file and put its filepath into an entry.
"""
def __init__(self, master, initialdir='', filetypes=()):
super().__init__(master)
self.filepath = tk.StringVar()
self._initaldir = initialdir
self._filetypes = filetypes
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10))
a = self._entry
self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse)
self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify)
self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14))
def _display_widgets(self):
self._label.pack(fill='y')
self._entry.pack(fill='x', expand=True)
self._button.pack(fill='y')
self._classify.pack(fill='y')
def retrieve_input(self):
#str1 = self._entry.get()
#a=a.replace('/','//')
print (str1)
def classify(self):
global a
newwin = tk.Toplevel(root)
newwin.geometry("500x500")
label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14))
label.pack()
canvas = tk.Canvas(newwin, height=300, width=300)
canvas.pack()
my_image = tk.PhotoImage(file=a, master=root)
canvas.create_image(150, 150, image=my_image)
newwin.mainloop()
def browse(self):
""" Browses a .png file or all files and then puts it on the entry.
"""
global a
a = fd.askopenfilename(initialdir=self._initaldir, filetypes=self._filetypes)
self.filepath.set(a)
if __name__ == '__main__':
root = tk.Tk()
labelfont = ('times', 10, 'bold')
root.geometry("500x500")
filetypes = (
('Portable Network Graphics', '*.png'),
("All files", "*.*")
)
file_browser = Browse(root, initialdir=r"~/Desktop", filetypes=filetypes)
file_browser.pack(fill='y')
root.mainloop()
P.S. Do change your initialdir. I changed it as I am not on Windows.

Resources