I'm very new to python and I don't know why but my code keeps crashing when I implement the listener specifically at the
with Listener(on_press=press) as listener: listener.join() and when it crashes it doesn't give me a error message
here's the entirety of my code:
import tkinter as tk
from tkinter.constants import LEFT, N, NE, NW, W
from PIL import Image, ImageTk
import tkinter.ttk as ttk
import time
from pynput.keyboard import Key, Controller
from pynput.keyboard import Listener
self = tk.Tk()
self.title('Key spammer')
self.iconbitmap("D:\Vs code repos\Key spammer\keyboard-icon.ico")
#Set the geometry of frame
self.geometry("350x550")
self.resizable(False, False)
#Button exit function
def exit_prog():
exit()
def press(key):
print(key)
#press interval
self.grid_rowconfigure(20, weight=1)
self.grid_columnconfigure(20, weight=1)
labelframe = ttk.Labelframe(self,text= "Press interval")
labelframe.grid(row=1, column=0, padx= 25, sticky=N)
class Lotfi(ttk.Entry):
def __init__(self, master=None, **kwargs):
self.var = tk.StringVar()
ttk.Entry.__init__(self, master, textvariable=self.var, **kwargs)
self.old_value = ''
self.var.trace('w', self.check)
self.get, self.set = self.var.get, self.var.set
def check(self, *args):
if self.get().isdigit():
# the current value is only digits; allow this
self.old_value = self.get()
else:
# there's non-digit characters in the input; reject this
self.set(self.old_value)
#Entry interval
hoursentry = Lotfi(labelframe, width= 10)
hoursentry.grid(row=1, column=1, padx= 5, pady= 10)
hoursentry.insert(0, '0')
hourslabel = ttk.Label(labelframe, text= "hours")
hourslabel.grid(row=1, column=2)
minutesentry = Lotfi(labelframe, width= 10)
minutesentry.grid(row=1, column=3)
minutesentry.insert(0, '0')
minuteslabel = ttk.Label(labelframe, text= "mins")
minuteslabel.grid(row=1, column=4)
secondsentry = Lotfi(labelframe, width= 10)
secondsentry.grid(row=1, column=5)
secondsentry.insert(0, '0')
secondeslabel = ttk.Label(labelframe, text= "secs")
secondeslabel.grid(row=1, column=6)
labelframekey = ttk.Labelframe(self,text= "Key options")
labelframekey.grid(row=2, column=0, padx= 25, pady= 25, sticky=NW)
#labelframekey.pack(side= LEFT)
keypress = ttk.Label(labelframekey, text= "Key pressed", font= 10)
keypress.grid(row=2, column=0, sticky= N)
with Listener(on_press=press) as listener:
listener.join()
class Keyreg(ttk.Entry):
def __init__(self, master=None, **kwargs):
self.var = tk.StringVar()
ttk.Entry.__init__(self, master, textvariable=self.var, **kwargs)
self.old_value = ''
self.var.trace('w', self.check)
self.get, self.set = self.var.get, self.var.set
def check(self, *args):
if press:
self.set(self.old_value)
#Keyreg = Keyreg(labelframekey, width= 10)
#keyreg.grid(row=2, column=1, sticky= N)
'''
#Creation of Option buttons
button = ttk.Button(self, text = 'Exit', command = exit_prog, width = 25)
button.grid(row=2, column=1,padx= 5, ipadx=15, ipady=10)
button2 = ttk.Button(self, text = 'Exit', command = exit_prog, width = 25)
button2.grid(row=2, column=2, ipadx=15, ipady=10)
button3 = ttk.Button(self, text = 'Exit', command = exit_prog, width = 25)
button3.grid(row=3, column=1, ipadx=15, ipady=10)
button4 = ttk.Button(self, text = 'Exit', command = exit_prog, width = 25)
button4.grid(row=3, column=2, ipadx=15, ipady=10)
'''
#Top menu for keybinds
tk.mainloop()
I tried to figure out the problem myself but when i imported it to another tab and used multiple different methods it still never crashed on those test
Please help me
You didn't show full error message so I don't know what is your real problem but I see one problem.
Code
with Listener(on_press=press) as listener:
listener.join()
runs code which waits for the end of listener and it stops rest of code
if you want to run it at the same time as tkinter then you should run as
with Listener(on_press=press) as listener:
tk.mainloop()
listener.join()
or more similar to threading (which is used by listener)
listener = Listener(on_press=press)
listener.start()
tk.mainloop()
listener.join()
Related
I'm trying to have a function perform an action using an if statement on a boolean_var().
Essentially, boolean_var.get() -> if True -> popup messagebox message, else -> Pass.
It's correctly "get"-ing the True statement and returning a 1, but will not enact the function I've called/pointed to afterward.
Any advice, or even pointing me to any specific reading material that may help would be greatly appreciated.
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
class WotcPull(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.master=master
self.NewWindow = tk.Toplevel(master)
self.NewWindow.title("Sources")
self.NewWindow.minsize(600, 400)
self.NewWindow.geometry("600x400")
self.NewWindow.columnconfigure(0, weight=1)
self.NewWindow.rowconfigure(0, weight=1)
self.NewWindow.rowconfigure(1, weight=15)
SourceOutputFrame = tk.Frame(
self.NewWindow,
bg="#414041",
borderwidth=1,
padx=3,
pady=10
)
SourceOutputFrame.grid(column=0, row=1, sticky=tk.N+tk.S+tk.W+tk.E)
SourceOutputFrame.columnconfigure(0, weight=1)
SourceOutputFrame.rowconfigure
SubOutputFrame = tk.Frame(
master=SourceOutputFrame,
bg="#414041",
borderwidth=1,
padx=3,
pady=10
)
SubOutputFrame.pack(side='top',fill='both',expand=1)
SubOutputButton["state"] = "disabled"
wotc_var = tk.BooleanVar()
wotc_yes = tk.Radiobutton(
master=SubOutputFrame,
text="Yes",
variable=wotc_var,
value=True,
foreground= "#C9C1B2",
background= "#414041",
borderwidth=1,
font=(25)
).grid(row=0, column=1, sticky=tk.NSEW)#, command=self.callback)
wotc_no = tk.Radiobutton(
master=SubOutputFrame,
text="No",
variable=wotc_var,
foreground= "#C9C1B2",
background= "#414041",
borderwidth=1,
font=(25),
value=False
).grid(row=0, column=2)#, command=self.callback)
def popupmsg():
messagebox.showinfo(message="success") #<- This will not work and I just can't figure out why
def SaveSources():
#messagebox.showinfo(message=wotc_var.get()) <- This works fine and returns 1 if wotc_yes is checked
if wotc_var.get() == 1:
#messagebox.showinfo(message=wotc_var.get()) <- Also works fine and returns 1 if wotc_yes is checked
popupmsg #<- the problem function that will not work for me
else:
messagebox.showinfo(message=wotc_var.get())
SaveSourcesButton = tk.Button(
master=SubOutputFrame,
text='Save',
command=SaveSources,
height=3,
width=15,
bg="#414041",
fg="#C9C1B2"
)
SaveSourcesButton.grid(
row=4,
column=0,
sticky=tk.EW,
padx=10,
pady=10
)
I am working on python exe application, I made a single class and methods inside single class, application working perfectly but when to add new implements track the code and implementing becomes clumsy so can any one give idea
My initial code presently working is:
from tkinter import *
from ttkthemes import themed_tk as tk
import tkinter as tkn
class Main_page:
"""Main Window this is configuration that exist when opens"""
def __init__(self, window):
# aligning the window details
self.window = window
self.window.geometry("1366x768+0+0")
self.window.title("Admin Page")
self.window.config(bg="gray")
# window assigning to full screen
self.window.attributes("-fullscreen", True)
self.window.bind('<Escape>', lambda event: self.window.attributes("-fullscreen", False))
self.window.bind('<F11>', lambda event: self.window.attributes("-fullscreen", True))
self.m_top_fra()
self.m_lef_fra()
self.m_body_fra()
def m_top_fra(self):
"""This is top Frame in exist on all pages"""
m_top_frame = Frame(self.window, height=70, width=1340)
m_top_frame.place(x=10, y=10)
def m_lef_fra(self):
"""This is side frame where the main handling buttons are placed
as billing, transaction details , settings"""
m_lef_frame = Frame(self.window, height=610, width=125, borderwidth=0)
m_lef_frame.place(x=10, y=85)
# Billing Button for left side
m_billing_but = Button(m_lef_frame, text="Billing", width=10, height=5, bg="#C6C1B9",
command=self.b_billing_page)
m_billing_but.place(x=25, y=20)
# manage Button for left side
m_manage_but = Button(m_lef_frame, text="Bill \n Manage", width=10, height=5, bg="#C6C1B9",
command=self.bm_bill_manage)
m_manage_but.place(x=25, y=140)
# view Button for left side
m_view_but = Button(m_lef_frame, text=" All\n View", width=10, height=5, bg="#C6C1B9",
command=self.v_view_page)
m_view_but.place(x=25, y=260)
# transactions Button for left side
m_transactions_but = Button(m_lef_frame, text="Transactions \n Settings", width=10, height=5, bg="#C6C1B9",
command=self.t_transaction_page)
m_transactions_but.place(x=25, y=380)
# exit Button for left side
m_exit_but = Button(m_lef_frame, text="Exit", width=10, height=5, bg="#C6C1B9",
command=self.exit_window)
m_exit_but.place(x=25, y=500)
def m_body_fra(self):
"""This is body frame where the initial info handles"""
self.body_frame = Frame(self.window, width=1210, height=610, bg="white")
self.body_frame.place(x=140, y=85)
# ________________Billing_____________
def b_billing_page(self):
"""when billing button is selected , the initial view of the page is opened"""
# this is for body frame to create the data in it
self.body_frame = Frame(self.window, width=1210, height=610, bg="#d4cfcf")
self.body_frame.place(x=140, y=85)
# top frame for some values to place
self.b_billing_top_frame = Frame(self.body_frame, width=1190, height=30)
self.b_billing_top_frame.place(x=10, y=10)
# body frame for the another wides
self.b_billing_body_frame = Frame(self.body_frame, width=1190, height=550, bg="white")
self.b_billing_body_frame.place(x=10, y=50)
def win():
"""initial initialization the page to view"""
master = tk.ThemedTk()
master.get_themes()
master.set_theme("clam")
Main(master)
master.mainloop()
if __name__ == "__main__":
win()
Same like billing, manage transactions and bill manager works.
But presently I am working as converting billing, manage, trans to different classes
from tkinter import *
from ttkthemes import themed_tk as tk
import tkinter as tkn
class Main:
def __init__(self, master):
self.master = master
self.master.geometry("1366x768+0+0")
self.master.title("Admin Page")
self.master.config(bg="gray")
# window assigning to full screen
self.master.attributes("-fullscreen", True)
self.master.bind('<Escape>', lambda event: self.master.attributes("-fullscreen", False))
self.master.bind('<F11>', lambda event: self.master.attributes("-fullscreen", True))
self.top_frame = Frame(self.master, height=70, width=1340)
self.top_frame.place(x=10, y=10)
self.lef_frame = Frame(self.master, height=610, width=125, borderwidth=0)
self.lef_frame.place(x=10, y=85)
self.body_frame = Frame(self.master, width=1210, height=610, bg="white")
self.body_frame.place(x=140, y=85)
self.value_buttons()
def value_buttons(self):
m_billing_but = Button(self.lef_frame, text="Billing", width=10, height=5, bg="#C6C1B9")
m_billing_but.place(x=25, y=20)
# manage Button for left side
m_manage_but = Button(self.lef_frame, text="Bill \n Manage", width=10, height=5, bg="#C6C1B9",
command=self.billing)
m_manage_but.place(x=25, y=140)
# view Button for left side
m_view_but = Button(self.lef_frame, text=" All\n View", width=10, height=5, bg="#C6C1B9")
m_view_but.place(x=25, y=260)
# transactions Button for left side
m_transactions_but = Button(self.lef_frame, text="Transactions \n Settings", width=10, height=5, bg="#C6C1B9")
m_transactions_but.place(x=25, y=380)
# exit Button for left side
m_exit_but = Button(self.lef_frame, text="Exit", width=10, height=5, bg="#C6C1B9")
m_exit_but.place(x=25, y=500)
def billing(self):
Billing(self.master)
class Billing(Main):
def __init__(self, master):
super().__init__(master)
self.master = master
print("billing called")
self.body_frame = Frame(self.master, width=1210, height=610, bg="white")
self.body_frame.place(x=140, y=85)
self.b_top_frame = Frame(self.body_frame, width=1190, height=30, bg="gray")
self.b_top_frame.place(x=10, y=10)
# body frame for the another wides
self.b_body_frame = Frame(self.body_frame, width=1190, height=550, bg="Gray")
self.b_body_frame.place(x=10, y=50)
def win():
"""initial initialization the page to view"""
master = tk.ThemedTk()
master.get_themes()
master.set_theme("clam")
Main(master)
master.mainloop()
if __name__ == "__main__":
win()
In the code shown here, when clicking billing button nothing happening.
Can anyone please help?
I have some Radiobuttons. Depending of what Radio button was selected I want to have different Combobox values. I don't know how I can solve the problem. In a further step I want to create further comboboxes which are dependend on the value of the first.
The following code creates the list of user, but it does not show up in the combobox.
For me it is difficult to understand where the right position of functions is, and if I need a lambda function nor a binding.
import tkinter as tk
from tkinter import ttk
import pandas as pd
import os
global version
global df_MA
df_MA = []
class Window(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.geometry('300x100')
self.title('Toplevel Window')
self.btn = ttk.Button(self, text='Close',command=self.destroy).pack(expand=True)
class App(tk.Tk):
def __init__(self,*args, **kwargs):
super().__init__()
# def load_input_values(self):
def set_department(department):
if department == "produktion":
working_df_complete = path_input_produktion
if department == "service":
working_df_complete = path_input_service
working_df_complete = pd.read_excel(working_df_complete)
working_df_complete = pd.DataFrame(working_df_complete)
'''set worker df'''
df_MA = working_df_complete.loc[:,'MA']
df_MA = list(df_MA.values.tolist())
def select_working_step():
return
'''Define Variable Bereich aofter clicking of radio button '''
'''SEEMS TO ME UNECCESSARY COMPLICATED, but I dont't know how to do it properly. I am no progammer'''
border = 10
spacey = 10
'''paths for input file'''
path_input_produktion = os.path.abspath('input_data\werte_comboboxen_produktion.xlsx')
path_input_service = os.path.abspath('input_data\werte_comboboxen_service.xlsx')
self.geometry('500x600')
'''Variablen for department'''
department = tk.StringVar()
department.set(" ")
'''place Frame department'''
self.rb_frame_abteilung = tk.Frame(self)
'''Radiobuttons for department'''
rb_abteilung_produktion = tk.Radiobutton(self.rb_frame_abteilung, text="Produktion", variable= department,
value="produktion", command= lambda: set_department(department.get()))
rb_abteilung_service = tk.Radiobutton(self.rb_frame_abteilung, text="Service", variable= department,
value="service", command= lambda: set_department(department.get()) )
rb_abteilung_produktion.pack(side="left", fill=None, expand=False, padx=10)
rb_abteilung_service.pack(side="left", fill=None, expand=False, padx =10)
self.rb_frame_abteilung.grid(row=5, column=1, sticky="nw", columnspan=99)
self.label_user = ttk.Label(self, text='user').grid(row=15,
column=15, pady=spacey,padx=border, sticky='w')
self.combobox_user = ttk.Combobox(self, width = 10, value= df_MA)
self.combobox_user.bind("<<ComboboxSelected>>", select_working_step)
self.combobox_user.grid(row=15, column=20, pady=spacey, sticky='w')
if __name__ == "__main__":
app = App()
app.mainloop()
ยดยดยด
I rewrote everything using indexes and removing global variables...
#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class App(tk.Tk):
"""Application start here"""
def __init__(self):
super().__init__()
self.protocol("WM_DELETE_WINDOW", self.on_close)
self.title("Simple App")
self.option = tk.IntVar()
self.departments = ('Produktion','Service')
self.df_MA_1 = ['Peter','Hans','Alfred']
self.df_MA_2 = ['Otto','Friedrich','Tanja']
self.init_ui()
self.on_reset()
def init_ui(self):
w = ttk.Frame(self, padding=8)
r = 0
c = 1
ttk.Label(w, text="Combobox:").grid(row=r, sticky=tk.W)
self.cbCombo = ttk.Combobox(w, values="")
self.cbCombo.grid(row=r, column=c, padx=5, pady=5)
r += 1
ttk.Label(w, text="Radiobutton:").grid(row=r, sticky=tk.W)
for index, text in enumerate(self.departments):
ttk.Radiobutton(w,
text=text,
variable=self.option,
value=index,
command= self.set_combo_values).grid(row=r,
column=c,
sticky=tk.W,
padx=5, pady=5)
r +=1
r = 0
c = 2
b = ttk.LabelFrame(self, text="", relief=tk.GROOVE, padding=5)
bts = [("Reset", 0, self.on_reset, "<Alt-r>"),
("Close", 0, self.on_close, "<Alt-c>")]
for btn in bts:
ttk.Button(b, text=btn[0], underline=btn[1], command = btn[2]).grid(row=r,
column=c,
sticky=tk.N+tk.W+tk.E,
padx=5, pady=5)
self.bind(btn[3], btn[2])
r += 1
b.grid(row=0, column=1, sticky=tk.N+tk.W+tk.S+tk.E)
w.grid(row=0, column=0, sticky=tk.N+tk.W+tk.S+tk.E)
def set_combo_values(self):
print("you have selected {0} radio option".format(self.option.get()))
self.cbCombo.set("")
if self.option.get() == 0:
self.cbCombo["values"] = self.df_MA_1
else:
self.cbCombo["values"] = self.df_MA_2
def on_reset(self, evt=None):
self.cbCombo.set("")
self.option.set(0)
self.set_combo_values()
def on_close(self,evt=None):
"""Close all"""
if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self):
self.destroy()
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main()
I am new to python, the above figure is two UI, I was trying to insert the two tab from the right side UI into the left side UI. But I had met some error and no idea how to solve.
Now below is the original coding of the left side UI
import tkinter as tkk
from tkinter import *
from tkinter import messagebox
import os.path
import hashlib
import sys
import time
import getpass
from tkinter import filedialog
import platform
import getpass
import os,sys
import tkinter.font as font
from tkinter import ttk
from tkinter import StringVar
import Consts
import shutil
class Page(tkk.Frame):
def __init__(self, *args, **kwargs):
tkk.Frame.__init__(self, *args, **kwargs)
def show(self):
self.lift()
class Page1(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs,bg='white')
my_system=platform.uname()
#computer information
comsys=my_system.system
comnode=my_system.node
comrel=my_system.release
comver=my_system.version
commac=my_system.machine
compro=my_system.processor
comuser=getpass.getuser()
label1 = tkk.Label(self, text="System: "+comsys,bg='white')
label1.grid(row=1,column=1,pady=10,sticky='w')
label2 = tkk.Label(self, text="Computer Name: "+comnode,bg='white')
label2.grid(row=2,column=1,pady=10,sticky='w')
label3 = tkk.Label(self, text="Release: "+comrel,bg='white')
label3.grid(row=3,column=1,pady=10,sticky='w')
label4 = tkk.Label(self, text="Version: "+comver,bg='white')
label4.grid(row=4,column=1,pady=10,sticky='w')
label5 = tkk.Label(self, text="Machine: "+commac,bg='white')
label5.grid(row=5,column=1, pady=10,sticky='w')
label6 = tkk.Label(self, text="Processor: "+compro,bg='white')
label6.grid(row=6,column=1, pady=10,sticky='w')
label7 = tkk.Label(self, text="Username: "+comuser,bg='white')
label7.grid(row=7,column=1,pady=10,sticky='w')
#computer usage hold first, no idea how to do
class Page2(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs,bg='white')
tabControl=ttk.Notebook(self)
qsFrame = ttk.Frame(tabControl)
fsFrame = ttk.Frame(tabControl)
csFrame = ttk.Frame(tabControl)
#tab
tabControl.add(qsFrame, text='Quick Scan')
tabControl.add(fsFrame, text='Full Scan')
tabControl.add(csFrame, text='Custom Scan')
tabControl.pack(expand=1,fill="both")
class Page3(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs,bg='white')
label = tkk.Label(self, text="This is page 3")
label.grid(row=2,column=1)
def mytools():
total, used, free = shutil.disk_usage("/")
print("Total:%d GB" %(total // (2**30)))
print("Used:%d GB" %(used // (2**30)))
print("Free:%d GB" %(free // (2**30)))
if free <= total/2:
clean = os.popen('Cleanmgr.exe/ sagerun:1').read()
#print(clean)
def btn1():
if __name__ =="__main__":
mytools()
button1=ttk.Button(self,text="Clean Up",command=btn1)
button1.grid(row=3,column=2)
class Page4(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs,bg='white')
label = tkk.Label(self, text="This is page 4")
label.grid(row=2,column=1)
class MainView(tkk.Frame):
def __init__(self, *args, **kwargs):
tkk.Frame.__init__(self, *args, **kwargs)
p1 = Page1(self)
p2 = Page2(self)
p3 = Page3(self)
p4 = Page4(self)
buttonframe = tkk.Frame(self)
container = tkk.Frame(self,bg='white')
buttonframe.pack(side="left", fill="x", expand=False)
container.pack(side="left", fill="both", expand=True)
buttonframe.grid_rowconfigure(0,weight=1)
buttonframe.grid_columnconfigure(0,weight=1)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p3.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p4.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
stats_btn = tkk.PhotoImage(file='C:/FYP/SecuCOM2022/icon&pic/stats.png')
scanner_btn = tkk.PhotoImage(file='C:\FYP\SecuCOM2022\icon&pic\scanner.png')
speedup_btn = tkk.PhotoImage(file='C:\FYP\SecuCOM2022\icon&pic\speedup.png')
settings_btn = tkk.PhotoImage(file='C:\FYP\SecuCOM2022\icon&pic\settings.png')
#logo
logo=tkk.PhotoImage(file="C:\FYP\SecuCOM2022\icon&pic\g (1).png")
label=tkk.Label(buttonframe,image=logo)
label.grid(row=0,column=0, padx=10,pady=10)
logo.image = logo
b1 = tkk.Button(buttonframe, image=stats_btn, command=p1.show, borderwidth=0)
b2 = tkk.Button(buttonframe, image=scanner_btn, command=p2.show, borderwidth=0)
b3 = tkk.Button(buttonframe, image=speedup_btn, command=p3.show, borderwidth=0)
b4 = tkk.Button(buttonframe, image=settings_btn, command=p4.show, borderwidth=0)
b1.image = stats_btn
b2.image = scanner_btn
b3.image = speedup_btn
b4.image = settings_btn
b1.grid(row=1,column=0,padx=10,pady=10)
b2.grid(row=2,column=0,padx=10,pady=10)
b3.grid(row=3,column=0,padx=10,pady=10)
b4.grid(row=4,column=0,padx=10,pady=10)
if __name__ == "__main__":
root= Tk()
main = MainView(root)
main.pack(side="top", fill="both", expand=True)
main.grid_rowconfigure(0,weight=1)
main.grid_columnconfigure(0,weight=1)
root.title("SecuCOM2022")
root.geometry("600x300")
root.maxsize(600,375)
root.minsize(600,375)
root.iconbitmap('C:\FYP\SecuCOM2022\icon&pic\g.png')
root.mainloop()
root.mainloop()
#GUI end`
Next below here is the right side UI coding, there are multiple files for it. I just show files related with the UI only.
Consts.py
ENTRY_WIDTH = 50
FileReportTab.py
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
from tkinter import StringVar
import time
import os.path
import sys
from VTPackage import Consts
class FileReportTab:
def __init__(self, root, frame, vtClient):
self.root = root
self.frame = frame
self.vtClient = vtClient
self.mainVTURLframe = ttk.LabelFrame(frame, text=' File report')
self.mainVTURLframe.grid(column=0, row=1, padx=8, pady=4)
ttk.Label(self.mainVTURLframe, text="Progress:").grid(column=0, row=1, sticky='W') # <== right-align
self.progressBar = ttk.Progressbar(self.mainVTURLframe, orient='horizontal', length=300, mode='determinate')
self.progressBar.grid(column=1, row=1)
ttk.Label(self.mainVTURLframe, text="File path:").grid(column=0, row=2, sticky='W') # <== right-align
self.filePath = StringVar()
filePathEntry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=self.filePath, state='readonly')
filePathEntry.grid(column=1, row=2, sticky='W')
ttk.Label(self.mainVTURLframe, text="Status:").grid(column=0, row=3, sticky='W') # <== right-align
self.status = StringVar()
statusEntry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=self.status, state='readonly')
statusEntry.grid(column=1, row=3, sticky='W')
ttk.Label(self.mainVTURLframe, text="Positive Indications:").grid(column=0, row=4, sticky='W') # <== right-align
self.positiveIndications = StringVar()
positiveIndicationsEntry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=self.positiveIndications, state='readonly')
positiveIndicationsEntry.grid(column=1, row=4, sticky='W')
ttk.Label(self.mainVTURLframe, text="SHA1:").grid(column=0, row=5, sticky='W') # <== right-align
self.sha1 = StringVar()
sha1Entry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=self.sha1, state='readonly')
sha1Entry.grid(column=1, row=5, sticky='W')
ttk.Label(self.mainVTURLframe, text="SHA256:").grid(column=0, row=6, sticky='W') # <== right-align
self.sha256 = StringVar()
sha256Entry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=self.sha256, state='readonly')
sha256Entry.grid(column=1, row=6, sticky='W')
chooseFileButton = ttk.Button(self.mainVTURLframe, text="Choose File", width=40, command=self._scanFile).grid(column=1, row=0)
self.scanCheckingTimeInterval = 25000 # This is the amount of time we are going to wait before asking VT again if it already processed our scan request
for child in self.mainVTURLframe.winfo_children():
child.grid_configure(padx=4, pady=2)
def showResults(self, results):
try:
#self.file_Path = self.filePath
self.sha1.set(results["sha1"])
self.sha256.set(results["sha256"])
self.positiveIndications.set(results["positives"])
if results["positives"] == 0:
messagebox.showwarning("Analysis Info","File is Safe.\nOur Scanners found nothing Malicious")
elif results["positives"] <= 5:
messagebox.showwarning("Analysis Alert", "Given File may be Malicious")
elif results["positives"] >= 5:
messagebox.showwarning("Analysis Alert", f"Given File is Malicious.\nAdvice you remove the file from your System!")
res = messagebox.askyesno("Analysis Alert","The given file is highly Malicious.\nDo you want to Delete it permanently?")
if res == 1:
print("Attemting to delete file...")
time.sleep(1)
os.remove(self.filePath1)
#if os.PathLike(_scanFile.filePath):
# os.remove(self.filePath)
else:
print("This file cannot be deleted. Please do not use the fie. It's Malicious")
except Exception as e:
messagebox.showerror('Error', e)
def checkStatus(self):
try:
self.scanResult = self.vtClient.get_file_report(self.scanID)
print(self.scanResult)
if self.scanResult["response_code"] == -2: # By reading the next line, you can understand what is the meaning of the -2 response ode
self.status.set("Scanning...")
self.progressBar['value'] = self.progressBar['value'] + 5
self.root.update_idletasks()
self.mainVTURLframe.after(self.scanCheckingTimeInterval, self.checkStatus)
else:
self.hasScanFinished = True
self.showResults(self.scanResult)
self.status.set("Finished!")
self.progressBar['value'] = 100
except Exception as e:
if "To much API requests" in str(e):
pass
def _scanFile(self):
try:
self.progressBar['value'] = 0
self.filePath1 = filedialog.askopenfilename(initialdir="/", title="Select file for VT", filetypes=(("EXE files", "*.exe"), ("all files", "*.*")))
if (self.filePath): # Only if the user chose a file, we will want to continue the process
self.filePath.set(self.filePath1)
self.status.set("Sending file...")
self.progressBar['value'] = 10
self.root.update_idletasks()
self.scanID = self.vtClient.scan_file(self.filePath1)
self.hasScanFinished = False
if not self.hasScanFinished:
self.scanResult = self.vtClient.get_file_report(self.scanID)
print(self.scanResult)
self.checkStatus()
# We could have been using time.sleep() or time.wait(), but then our UI would get stuck.
# by using after, we are initiating a callback in which does not blocks our event loop
except Exception as e:
messagebox.showerror('Error', e)
URLreportTab.py
from tkinter import ttk
from tkinter import StringVar
from VTPackage import Consts
class URLreportTab:
def __init__(self, root, frame, vtClient):
self.root = root
self.frame = frame
self.mainVTURLframe = ttk.LabelFrame(frame, text=' URL report tab!')
# using the tkinter grid layout manager
self.mainVTURLframe.grid(column=0, row=0, padx=8, pady=4)
ttk.Label(self.mainVTURLframe, text="URL:").grid(column=0, row=0, sticky='W') # What does sticky does? Sticky sayes where to stick the label to : N,S,E,W
urlEntry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH)
urlEntry.grid(column=1, row=0, sticky='E')
ttk.Label(self.mainVTURLframe, text="Positive Indications:").grid(column=0, row=1, sticky='W') # <== right-align
Positive = StringVar()
PositiveEntry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=Positive, state='readonly')
PositiveEntry.grid(column=1, row=1, sticky='W')
ttk.Label(self.mainVTURLframe, text="Detections:").grid(column=0, row=2, sticky='W') # <== right-align
detections = StringVar()
detectionsEntry = ttk.Entry(self.mainVTURLframe, width=Consts.ENTRY_WIDTH, textvariable=detections, state='readonly')
detectionsEntry.grid(column=1, row=2, sticky='W')
self.notificationFrame = ttk.LabelFrame(self.frame, text=' Notifications', width=40)
# using the tkinter grid layout manager
self.notificationFrame.grid(column=0, row=1, padx=8, pady=10, sticky='W')
ttk.Label(self.notificationFrame, text="Errors:").grid(column=0, row=0, sticky='W') # <== increment row for each
Error = StringVar()
ErrorEntry = ttk.Entry(self.notificationFrame, width=Consts.ENTRY_WIDTH, textvariable=Error, state='readonly')
ErrorEntry.grid(column=1, row=0, sticky='W')
def _cleanErrorMessage(): # We could have been doing this without a function, but it is more neat that way
Error.set("")
def _getReport():
# the _ notation before a function means that this function is internal to the class only. As python cannot really prevent you from using it outside the class (as C# for example) the notation is being used to warn other developers not to call this function outside the class
try:
_cleanErrorMessage() # Starting with cleaning the error message bar
if not urlEntry.get():
print('Please enter a URL')
Error.set("Please enter a URL!")
return
urlToCheck = urlEntry.get()
response = vtClient.get_url_report(urlToCheck)
print(response)
Positive.set(response["positives"])
scans = response["scans"]
findings = set()
for key, value in scans.items():
if value["detected"]:
findings.add(value["result"])
detections.set(",".join([str(finding) for finding in findings]))
except Exception as e:
print(e)
Error.set(e)
checkURLinVTButton = ttk.Button(self.mainVTURLframe, text='Check Now!', command=_getReport).grid(column=2, row=0)
# Instead of setting padding for each UI element, we can just iterate through the children of the main UI object.
for child in self.mainVTURLframe.winfo_children():
child.grid_configure(padx=4, pady=2)
for child in self.notificationFrame.winfo_children():
child.grid_configure(padx=4, pady=2)
VTApp.py
import tkinter as tk
import configparser
from tkinter import Menu
from tkinter import ttk
from tkinter import messagebox
from VTPackage import URLreportTab
from VTPackage import FileReportTab
from VTPackage import VTClient
config = configparser.ConfigParser()
config.read('config.ini')
class VTApp:
def __init__(self):
# Loading the config file
self.config = configparser.ConfigParser()
self.config.read('config.ini')
self.virusTotalAPIkey = config['VirusTotal']['apiKey']
self.vtClient = VTClient.VTClient(self.virusTotalAPIkey)
self.root = tk.Tk()
self.root.title("Virus Total UI")
self.menuBar = Menu()
self.root.config(menu=self.menuBar)
self.fileMenu = Menu(self.menuBar, tearoff=0)
self.fileMenu.add_command(label="New")
self.fileMenu.add_separator()
self.menuBar.add_cascade(label="File", menu=self.fileMenu)
if not self.vtClient.is_API_key_valid():
messagebox.showerror('Error', "API key is not valid! Check your config file")
def _quit():
self.root.quit() # The app will exist when this function is called
self.root.destroy()
exit()
self.fileMenu.add_command(label="Exit", command=_quit) # command callback
self.tabControl = ttk.Notebook(self.root) # Create Tab Control
self.urlFrame = ttk.Frame(self.tabControl)
self.urlTab = URLreportTab.URLreportTab(self.root, self.urlFrame, self.vtClient)
self.tabControl.add(self.urlFrame, text='URL')
self.fileFrame = ttk.Frame(self.tabControl)
self.fileTab = FileReportTab.FileReportTab(self.tabControl, self.fileFrame, self.vtClient)
self.tabControl.add(self.fileFrame, text='File')
self.tabControl.pack(expand=1, fill="both") # Pack to make visible
def start(self):
self.root.mainloop()
Main.py
from VTPackage import VTApp
vtApp = VTApp.VTApp()
vtApp.start()
This is the original code, Sorry for the spacing error, I copy&paste from vsc and it seem like the got some spacing error after Class. So basically this is the original code and I try like import VTApp and code inside class Page2 like
vtApp = VTApp.VTApp()
vtApp.start()
and change some coding in the VTApp.py but it doesn't work.... Does anyone know how to make the script works? I been trying and trying for a week and still couldn't get the solution.
You cannot move a widget from one window to another in tkinter. You will have to recreate the tab in the other window.
This is a dialog form class :
** update full workable source code showing the problem
from tkinter import *
class SGForm:
created_form = False
def __init__(self, root, title=""):
self.form = Toplevel(root)
self.form.wm_title(title)
self.input = dict()
self.var = StringVar()
SGForm.created_form = True
def getform(self):
return self.form
def addinput(self, name, text ,var = None):
p = Frame(self.form)
p.pack(side="top", fill="both", expand=True, padx=10, pady=10)
l = Label(p, text=text)
l.pack(side="left", fill="both", expand=True, padx=10, pady=10)
self.input[name] = Entry(p, textvariable=var)
self.input[name].pack(side="left", fill="both", expand=True, padx=10, pady=10)
def addbutton(self, text, signal, func):
p = Frame(self.form)
p.pack(side="top", fill="both", expand=True, padx=10, pady=10)
b = Button(p, text=text)
b.pack(side="left", fill="both", expand=True, padx=10, pady=10)
b.bind(signal, func)
def showandreturn(self):
value = dict()
value['firstname'] = self.var.get()
SGForm.created_form = False
return value
def closeform(self, event):
self.form.destroy()
def customform(self):
self.addinput('entfirstname', 'frist name', self.var)
self.addbutton('close','<Button-1>', self.closeform)
#example calling dialog class
root = Tk()
def evntshow(event):
form = SGForm(root)
form.customform()
root.wait_window(form.getform())
test = form.showandreturn()
print(test)
button = Button(root, text='show')
button.pack()
button.bind('<Button-1>', evntshow)
root.mainloop()
Each time the button get pressed eventaddperson get triggered, when exiting the function the button animation of the main window get stuck on press status, I am looking for a way to refresh the gui or what if I am doing something wrong how to fix it?
If I use command= instead of bind() then problem disappers
BTW: if you use command= then def evntshow()has to be without event
def evntshow(): # <--- without event
form = SGForm(root)
form.customform()
root.wait_window(form.getform())
test = form.showandreturn()
print(test)
# use `command=` instead of `bind('<Button-1>',...)
button = Button(root, text='show', command=evntshow)
button.pack()
I was experiencing kind of laggy button animations when using bind() as well, switching to command= made it a look a lot better!
from tkinter import *
import time
def func1():
print('waiting for 1 second...')
time.sleep(1)
def func2(event):
print('waiting for 1 second...')
time.sleep(1)
root = Tk()
# button animation runs smoothly
Button1 = Button(root, text="button with command=", command=func1)
Button1.pack()
Button2 = Button(root, text="button with bind()") # button animation does not occur
Button2.bind('<Button-1>', func2)
Button2.pack()
root.mainloop()
I am working with python 3.6 and windows 10