How to position Layouts in tkinter? - python

I would like to make the following GUI.. each python class was made and working well with the name suggested below.
For example, elements_structure related class is looking like
class Elements_Structure():
def __init__(self, root):
super(Elements_Structure, self).__init__(root)
self.create_GUI()
def create_GUI(self):
label = Label(self, text="Elements Structure", font=("Arial",12)).grid(row=0, sticky=W)
cols = ('L#', 'Layer Name', 'Material', 'Refractive Index', 'Thickness', 'Unit')
listBox = Treeview(self, columns=cols, show='headings')
and the main entry code is looking like,
from tkinter import *
from components.elements_structure import *
from components.emission_layer import *
from components.emission_zone_setting import *
from components.file_tab import *
from components.logo_image import *
def main(root):
top_frame = Frame(root, width=1980, height=780).grid(rowspan=4, columnspan=4)
bottom_frame = Frame(root, width=1980, height=230).grid(columnspan=4)
elements_structure_graph = Frame(top_frame, width=480, height=780).grid(row=0, column=0, rowspan=4)
elements_structure = Frame(top_frame, width=960, height=690).grid(row=0, column=1, rowspan=3, columnspan=2)
logo_image = Frame(top_frame, width=480, height=230).grid(row=0, column=2)
logo_properties = Frame(top_frame, width=480, height=230).grid(row=1, column=2)
logo_execute = Frame(top_frame, width=480, height=230).grid(row=2, column=2)
emission_layer = Frame(top_frame, width=1440, height=100).grid(row=2, column=2, colspan=3)
emission_layer_graph = Frame(bottom_frame, width=480, height=290).grid(row=0, column=0)
emission_zone_setting = Frame(bottom_frame, width=480, height=290).grid(row=0, column=2)
emission_zone_setting_graph = Frame(bottom_frame, width=480, height=290).grid(row=0, column=1)
logo_project_info = Frame(bottom_frame, width=480, height=290).grid(row=0, column=3)
root.title("JooAm Simulator")
root.geometry('{}x{}'.format(1920, 1080))
root.mainloop()
if __name__ == '__main__':
root = Tk()
File_Tab(root)
main(root)
But I seemed to miss the link between the class and the tkinter window object.
How can I make the above structure with the library tkinter?
Thank you in advance~!!

Lot to deal with here. Can't work on the code without the components file.
Most on what is in main should be in create_GUI.
I like to start with something like:
class OLED_Display:
def init(self, master):
self.master = master
self.frame = tk.Frame(self.master)
bg_color='light green'
self.button1 = tk.Button(self.frame, text = 'Constants',
width = 35, command = 'ANY USER FUNCTION', bg=bg_color)
You can try from there or provide more info.

Related

How to compile python EXE script that can be used on windows computer without python programme

I am struggling ensure python script work on windows computer that does not have python installer. The script below only works on the computer with python software not sure where l am going wrong. Result is if uploaded on another computer no pictures or path is wrong. l am new to python can you please help as l dont know where l am going wrong. Thanks in advance
"""
from tkinter import*
import tkinter as tk
from tkinter import ttk
from datetime import datetime
windo = Tk()
windo.resizable(width=FALSE, height=FALSE)
windo.geometry("600x400")
windo.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
def han():
print("Forms to be completed")
import tkinter as tk
from tkinter import ttk
from datetime import datetime
root = Tk()
root.resizable(width=FALSE, height=FALSE)
root.geometry("680x670")
root.iconbitmap(r"C:\Users\breada\OneDrive\Desktop\Notes\image\Healthcare.ico")
house = "Mhungu"
fun8 = Label(root, text="Running times comp :")
fun8.place(x=10,y=120)
var32 = IntVar()
chekbtn_1 = Checkbutton(root ,text="Yes", variable=var32)
chekbtn_1.place(x=180,y=120)
var33 = IntVar()
chekbtn_2 = Checkbutton(root ,text="No", variable=var33)
chekbtn_2.place(x=230,y=120)
def cli(value):
print("Severity of aggression")
print(value)
def clic(value):
print("Area of aggression")
print(value)
def click(value):
print("Nature of aggression")
print(value)
def save_funct():
print("Saved")
frame = LabelFrame(root, padx=5, pady=5)
v = tk.StringVar()
v.set("None")
lab2 = Label(frame, text="Select Level of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame, variable=v,value="1-No Concern", text="1-No Concern", command=lambda:cli(v.get()))
radioButton2 = Radiobutton(frame, variable=v, value="2-Not Severe",text="2-Not Severe",command=lambda:cli(v.get()) )
radioButton3 = Radiobutton(frame, variable=v, value="3-Slightly Severe",text="3-Slightly Severe",command=lambda:cli(v.get()) )
radioButton4 = Radiobutton(frame, variable=v, value="6-Extremely Severe",text="6-Extremely Severe",command=lambda:cli(v.get()) )
radioButton5 = Radiobutton(frame, variable=v,value="5-Severe", text="5-Severe", command=lambda:cli(v.get()))
radioButton6 = Radiobutton(frame, variable=v,value="4-Fairly Severe", text="6-Fairly Severe", command=lambda:cli(v.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame.place(x=35, y=155)
frame1 = LabelFrame(root, padx=5, pady=5)
vv = tk.StringVar()
vv.set("None")
lab2 = Label(frame1, text="Areas of Aggressions", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame1, variable=vv,value="Lounge", text="Lounge", command=lambda:clic(vv.get()))
radioButton2 = Radiobutton(frame1, variable=vv, value="Kitchen",text="Kitchen",command=lambda:clic(vv.get()) )
radioButton3 = Radiobutton(frame1, variable=vv, value="Bedroom 1",text="Bedroom 1",command=lambda:clic(vv.get()) )
radioButton4 = Radiobutton(frame1, variable=vv, value="Bedroom 2",text="Bedroom 2",command=lambda:clic(vv.get()) )
radioButton5 = Radiobutton(frame1, variable=vv,value="Bedroom 3", text="Bedroom 3", command=lambda:clic(vv.get()))
radioButton6 = Radiobutton(frame1, variable=vv,value="Dinning ", text="Dinning", command=lambda:clic(vv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame1.place(x=35, y=255)
frame2 = LabelFrame(root, padx=5, pady=5)
vvv = tk.StringVar()
vvv.set("None")
lab2 = Label(frame2, text="Nature of Aggression", fg="blue", font=("Arial", 10))
lab2.pack()
radioButton1 = Radiobutton(frame2, variable=vvv,value="Punching", text="Punching", command=lambda:click(vvv.get()))
radioButton2 = Radiobutton(frame2, variable=vvv, value="Kicking",text="Kicking",command=lambda:click(vvv.get()) )
radioButton3 = Radiobutton(frame2, variable=vvv, value="Pushing ",text="Pushing",command=lambda:click(vvv.get()) )
radioButton4 = Radiobutton(frame2, variable=vvv, value="Forceful",text="Forceful",command=lambda:click(vvv.get()) )
radioButton5 = Radiobutton(frame2, variable=vvv,value="Punching Walls", text="Punching Walls", command=lambda:click(vvv.get()))
radioButton6 = Radiobutton(frame2, variable=vvv,value="Clinch fists ", text="Clinch fists", command=lambda:click(vvv.get()))
radioButton1.pack(side=LEFT)
radioButton2.pack(side=LEFT)
radioButton3.pack(side=LEFT)
radioButton4.pack(side=RIGHT)
radioButton5.pack(side=RIGHT)
radioButton6.pack(side=RIGHT)
frame2.place(x=35, y=355)
buttnn = Button(root, text="Save", width=10, height=2, fg= "blue",command=save_funct)
buttnn.place(x=570, y=615)
root.mainloop()
def st_ii():
print("Redirected")
canvas=Canvas(width=400,height=200, bg="blue")
canvas.place(x=200,y=130)
photo=PhotoImage(file="C:\\Users\\breada\\OneDrive\\Desktop\\Forest.png")
canvas.create_image(0,0,image=photo, anchor=NW)
toolbar = Frame(windo, bg="powder blue", padx=3, pady=20)
insertButt= Button(toolbar,text = "A-Form",command =han)
insertButt.pack(side=LEFT, padx=6,pady=2)
shift_planButt = Button(toolbar, text= "B-Form",command =st_ii)
shift_planButt.pack(side=LEFT, padx=6,pady=2)
toolbar.pack(side=TOP,fill=X)
windo.mainloop()
"""
If you compile your script into an executable file, for example by using "auto-py-to-exe", then the resulting .exe-file can be run on any computer with the same architecture as the one you created the .exe file on.
You can include other files or folders containing pictures or icons using a simple GUI.
you can install it with pip:
$ pip install auto-py-to-exe
or directly from github:
https://github.com/brentvollebregt/auto-py-to-exe

Insert the control tab from one UI to another UI

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.

Tkinter LabelFrames don't show up

When i want to layout my frames the Labels don't show up. I can't seem to solve it. For some reason it does show op the entries that i've made. Can somebody please help me.
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
class main_screen():
def __init__(self, master):
self.master = master
self.master.title("Roboframe")
self.master.geometry("650x650")
self.create_frames()
self.create_entries()
def create_frames(self):
self.top = Frame(self.master).grid(row=0,column=0)
self.bottom = Frame(self.master).grid(row=0, column=0)
self.set_paths = LabelFrame(self.master, text="Set Path", padx=10, pady=10).grid(row=0,column=0)
self.options = LabelFrame(self.master, text="Options", padx=10, pady=10).grid(row=0,column=0)
def create_entries(self):
python_path = StringVar(self.set_paths, "C:/Python37/python.exe")
robot_path = StringVar(self.set_paths, "C:/ws/cmge.automation/RobotFrameworkCMGE")
self.set_path_python = Entry(self.set_paths, width=60, textvariable=python_path).grid(row=0,column=0)
self.set_path_robot = Entry(self.set_paths, width=60, textvariable=robot_path).grid(row=1, column=0)
root = tk.Tk()
app = main_screen(root)
root.mainloop()
Output of code shown above
The thing i'm rewritting the code for because it is a mess
The second picture i've also made myself. But the code is a giant mess.
You have to make an object of the widget not the grid function of the widget. Grid returns nothing so naturally none of them will show up. I believe this is what you wanted:
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
class main_screen():
def __init__(self, master):
self.master = master
self.master.title("Roboframe")
self.master.geometry("650x650")
self.create_frames()
self.create_entries()
def create_frames(self):
# you have grided all of your frames and label frames on the same row and column
self.top = Frame(self.master)
self.top.grid(row=0,column=0)
self.bottom = Frame(self.master)
self.bottom.grid(row=0, column=0)
self.set_paths = LabelFrame(self.master, text="Set Path", padx=10, pady=10)
self.set_paths.grid(row=0,column=0)
self.options = LabelFrame(self.master, text="Options", padx=10, pady=10)
self.options.grid(row=0,column=0)
def create_entries(self):
python_path = StringVar(self.set_paths, "C:/Python37/python.exe")
robot_path = StringVar(self.set_paths, "C:/ws/cmge.automation/RobotFrameworkCMGE")
self.set_path_python = Entry(self.set_paths, width=60, textvariable=python_path)
self.set_path_python.grid(row=0,column=0)
self.set_path_robot = Entry(self.set_paths, width=60, textvariable=robot_path)
self.set_path_robot.grid(row=1, column=0)
root = tk.Tk()
app = main_screen(root)
root.mainloop()
Also a couple of things:
You have imported tkinter twice in two different ways, just use one of them
You are griding both of the LabelFrames and frames on the same row and column but since "self.options" does not contain anything it is not going to show up, be careful later on
This will display both LabelFrames, the second with a dummy Entry widget.
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
class main_screen():
def __init__(self, master):
self.master = master
self.master.title("Roboframe")
self.master.geometry("650x650")
self.create_frames()
self.create_entries()
def create_frames(self):
self.set_paths = LabelFrame(self.master, text="Set Path", padx=10, pady=10)
self.set_paths.grid(row=0,column=0)
self.options = LabelFrame(self.master, text="Options", padx=10, pady=10)
self.options.grid(row=1,column=0)
def create_entries(self):
python_path = StringVar(self.set_paths, "C:/Python37/python.exe")
robot_path = StringVar(self.set_paths, "C:/ws/cmge.automation/RobotFrameworkCMGE")
self.set_path_python = Entry(self.set_paths, width=60, textvariable=python_path)
self.set_path_python.grid(row=0,column=0)
self.set_path_robot = Entry(self.set_paths, width=60, textvariable=robot_path)
self.set_path_robot.grid(row=1, column=0)
self.test = Entry(self.options, width=60)
self.test.grid(row=1, column=1)
root = tk.Tk()
app = main_screen(root)
root.mainloop()

AttributeError: class Frame has no attribute 'StringVar'

So i have this code below. Ive tried a various form of how to get to work the StringVar, but nothing happened. And thats why a turned to you oh, god of stackoverflow. Pls show me how to make it throught. I have an input in Entry1 and I need to get this input into an sql ( ive cut it out because of its uninportant) and return the value of it and write it into Entry1 insted of the original input. Please Lord of SO halp me!
#!usr/bin/python
#-*- coding: utf-8 -*-
import os
import time
import mysql.connector
import getpass
import smtplib
from email.mime.text import MIMEText
global atado_kartya_input
global atvevo_kartya_input
from PIL import Image, ImageTk
#from Tkinter import Tk, Text, TOP, BOTH, X, N, LEFT
from Tkinter import *
from Tkinter import Tk as tk
from ttk import Frame, Style, Entry, Label
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.addbutton()
def addbutton(self):
b = Button( self, text= "Get!", width = 10, command= self.callback)
b.pack()
def callback(self):
#07561847
#tk()
atvevoText = Frame.StringVar()
atvevoText = atvevo(self.entry1.get()) #from the "atvevo" function it gets a name of a worker form an SQL statement
self.entry1.delete(0, 'end')
self.entry1.insert(0, atvevoText)
#self.entry1 = Entry(self, textvariable = atvevoText )
print(atvevoText)
def initUI(self):
self.parent.title("Pozi")
self.pack(fill = BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=X)
lbl1 = Label(frame1, text = "ĂtadĂł kártyája", width = 30)
lbl1.pack(side = LEFT, padx=5, expand=True)
self.entry1 = Entry(frame1)
self.entry1.pack(side = LEFT, padx=5, expand=True)
frame2 = Frame(self)
frame2.pack(fill=X)
lbl2 = Label(frame2, text = "ĂrvevĹ‘ kártyája", width = 30)
lbl2.pack(side = LEFT, padx=5, expand=True)
entry2 = Entry(frame2)
entry2.pack(side = LEFT, padx=5, expand=True)
frame3 = Frame(self)
frame3.pack(fill=X)
lbl3 = Label(frame3, text = "ĂrvevĹ‘ kártyája", width = 30)
lbl3.pack(side = LEFT, padx=5, expand=True)
entry3 = Entry(frame3)
entry3.pack(side = LEFT, padx=5, expand=True)
frame4 = Frame(self)
frame4.pack(fill=BOTH, expand = True)
lbl4 = Label(frame4, text = "Title", width = 30)
lbl4.pack(side = LEFT, anchor=N, padx=5, pady=5)
txt = Text(frame4)
txt.pack(fill = BOTH, padx=5, pady=5, expand=True)
#Style().configure("TFrame", backgroung = "#333") # tframe háttérszinét beállítjuk90%
def main():
root = Tk()
root.geometry("550x450+300+300") # width x heigth + x + y (on screen)
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
Update
I have to change in a way like that:
def callback(self):
#07561847
#tk()
atvevoText = StringVar()
number = self.entry1.get()
self.entry1.delete(0, 'end')
#self.entry1.insert(0, atvevoText)
self.entry1 = Entry(self, textvariable = atvevoText )
atvevoText = atvevo(number)
print(atvevoText)
*And with it i got nothing to back nor error nor the value :( *
Change
Frame.StringVar()
to
StringVar()
Since StringVar is a class inside Tkinter(not tested just googled)

Tkinter - set label for listbox

I'm trying to do a simple GUI in Tkinter. I have a Listbox there and I want the user to know what kind of data is in the Listbox so I want to set a label for it (upper).
The problem is that when I set a label, this Listbox disappears.
l = Label(multiple_choose_days_listbox, textvariable=label_day_listbox , anchor=NW, justify='center')
l.pack()
The solution is probably obvious but I'm new in Tkinter.
Do you have any advices?
import Tkinter
import tkSimpleDialog
from Tkinter import *
import db
import ttkcalendar
class CalendarDialog(tkSimpleDialog.Dialog):
"""Dialog box that displays a calendar and returns the selected date"""
def __init__(self, master):
self.calendar = ttkcalendar.Calendar(master)
# self.calendar.pack()
#property
def result(self):
return self.calendar.selection
def pack(self,**kwargs):
self.calendar.pack(**kwargs)
states_list = db.get_states()
bought_days_before_list = db.get_bought_days_before()
multiple_choose_length_of_trips_list = db.get_lengths_of_trips()
def main():
root = Tkinter.Tk()
root.wm_title("CalendarDialog Demo")
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.geometry("1000x500")
top = Frame(root)
bottom = Frame(root)
top.pack(side=TOP)
bottom.pack(side=BOTTOM, fill=BOTH, expand=True)
cd_1 = CalendarDialog(root)
cd_2 = CalendarDialog(root)
cd_1.pack(in_=top, side=LEFT)
cd_2.pack(in_=top, side=LEFT)
multiple_choose_states_listbox = Listbox(root, selectmode=EXTENDED)
multiple_choose_states_listbox.grid(row=20, columns=1)
multiple_choose_days_listbox = Listbox(root, selectmode=EXTENDED)
multiple_choose_length_of_trips_list_listbox = Listbox(root, selectmode=EXTENDED)
label_day_listbox = StringVar()
label_day_listbox.set("LABEL")
l = Label(multiple_choose_days_listbox, textvariable=label_day_listbox , anchor=NW, justify='center')
l.pack()
multiple_choose_days_listbox.pack(in_=top,side=LEFT)
multiple_choose_states_listbox.pack()
multiple_choose_length_of_trips_list_listbox.pack()
for item in states_list:
multiple_choose_states_listbox.insert(END, item)
for item in bought_days_before_list:
multiple_choose_days_listbox.insert(END, item)
def get_result_dict():
date_from = cd_1.result
date_to = cd_2.result
states = [states_list[i] for i in multiple_choose_states_listbox.curselection()]
bought_days_before = [bought_days_before_list[i] for i in multiple_choose_days_listbox.curselection()]
length_of_trip = [states_list[i] for i in multiple_choose_length_of_trips_list.curselection()]
res_dict = {
'date_from': date_from,
'date_to': date_to,
'states': states,
'bought_days_before': bought_days_before,
'length_of_trip': length_of_trip,
}
return res_dict
button = Tkinter.Button(root, text="Generate", command=get_result_dict)
button.pack()
root.update()
root.mainloop()
if __name__ == "__main__":
main()
It should be
l = Tkinter.Label(root, text="Label")

Categories

Resources