Class __init__ seems to be starting other Functions within the class? - class

I'm trying to code a GUI with two login functions and then a third window with a bunch of widgets. The issue I've run into is since I want to take entry values and retrieve them from another function, I figured I should use a Class. However, when I'm running my code, it seems to pop open all of the other Functions in the starting class.
import sys
from tkinter import *
class Gui():
def __init__(self, root):
self.root=root
self.entry = Entry(root)
stvar=StringVar()
stvar.set("one")
self.canvas=Canvas(root, width=300, height=300, background='white')
self.canvas.grid(row=1,column=0, columnspan = 4)
frame = Frame(self.root)
frame.grid(row=2,column=0, sticky="s")
frame2 = Frame(self.root)
frame2.grid(row=0,column=0, sticky = "n")
self.option=OptionMenu(frame, stvar, "one", "two", "three")
label1=Label(frame, text="Stock Mean:").grid(row=2,column=0, sticky="nw")
label2=Label(frame2, text="Stocks").grid(row=0,column=0,sticky = "w")
self.option=OptionMenu(frame2, stvar, "StockOne", "StockTwo", "StockThree").grid(row=1, column=0, sticky = "w")
label3= Label(frame, text="Std Variance").grid(row=2, column=1)
label4= Label(frame, text="Buy Price").grid(row=2, column=2)
label5=Label(frame, text="Sell Price").grid(row=2,column=3)
label6= Label(frame2, text="Auto/Manual").grid(row=0, column=3,sticky= "e")
labelSpace1 = Label(frame2, text= " ").grid(row=0, column = 1, columnspan = 2)
label7 = Label(frame, text = "Sample Mean").grid(row = 3, column = 0)
label8 = Label(frame, text = "Sample Std Variance").grid(row = 3, column = 1)
label9 = Label(frame, text = "Sample Buy Price").grid(row = 3, column = 2)
label10 = Label(frame, text = "Sample Sell Price").grid(row = 3, column = 3)
class Verification():
def __init__(self):
##First Window
self.master = master
label1 = Label(self.master, text = "Username:")
label1.pack()
user = Entry(self.master)
user.pack()
label2 = Label(self.master, text = "Password:")
label2.pack()
password = Entry(self.master)
password.pack()
button = Button(self.master, text = "Login", command = Verification.verify1(self))
self.master.title("Stock Program")
self.master.geometry("400x500")
button.pack()
##self.master.mainloop()
def verify1(self):
self.root1=Toplevel(self.master)
self.root1.title("Stock Broker Login")
self.root1.geometry("500x500")
##Broker Menu
variable = StringVar(self.root1)
variable.set("TestOne")
OPTIONS = ["One" , "Two", "Three", "Four"]
self.m = OptionMenu(self.root1, variable, OPTIONS)
self.m.pack()
##Login for Broker Account
label3 = Label(self.root1, text = "Username:")
label3.pack()
self.user2 = Entry(self.root1)
self.user2.pack()
label4 = Label(self.root1, text = "Password:")
label4.pack()
self.password2 = Entry(self.root1)
self.password2.pack()
self.user2info = self.user2.get()
self.pass2info = self.password2.get()
button2 = Button(self.root1, text = "Login", command =Verification.verify2(self) )
button2.pack()
## button3 = Button(self.root1, text = "Close", command = Verification.closewindow(self))
## button3.pack()
## def closewindow(self):
## self.master.destroy()
def verify2(self):
##if (self.user2info)=="Name":
self.GraphWindow()
##print (self.pass2info)
def GraphWindow(self):
self.root2 =Tk()
gui =Gui(self.root2)
##self.root2.mainloop()
if __name__ == '__main__':
master=Tk()
start = Verification()
master.mainloop()
The first code I used (Which avoided using this Class) did not run into this issue, so the secondary login window would only pop open if the first Login button was trigger( Which would trigger the command Verify1).
Does anyone know how I can prevent the other functions from triggering? Thanks!

In your __init__ method you are calling the methods that you're attempting to use as callbacks, rather than simply passing the function object. EX:
command = Verification.verify1(self)
Should instead be
command = self.verify1
You make the same mistake in verify1 with your binding to verify2

Related

How can I use Telescope.nvim to complete a path in insert mode?

Fzf.vim implements a fuzzy finder in insert mode, extending the native ins-completion functionality.
For example: in insert mode, we can map <c-x><c-f> to enable Fzf.vim to fuzzy find and insert file names with relative paths (fzf-complete-path). The same functionalities are implemented for words (fzf-complete-word) and lines (fzf-complete-line) completions.
Here are the Fzf.vim mapping example of these functions:
" Insert mode completion
imap <c-x><c-k> <plug>(fzf-complete-word)
imap <c-x><c-f> <plug>(fzf-complete-path)
imap <c-x><c-l> <plug>(fzf-complete-line)
How can I set the same behavior with Telescope.nvim?
You can define a custom action and map it to a key to execute it in Telescope.
I've written a set of actions for this task (to insert file paths in the current buffer): telescope-insert-path.nvim
You just need to make your custom mappings in the require'telescope'.setup().
local path_actions = require('telescope_insert_path')
require('telescope').setup {
defaults = {
mappings = {
n = {
["pi"] = path_actions.insert_relpath_i_insert,
["pI"] = path_actions.insert_relpath_I_insert,
["pa"] = path_actions.insert_relpath_a_insert,
["pA"] = path_actions.insert_relpath_A_insert,
["po"] = path_actions.insert_relpath_o_insert,
["pO"] = path_actions.insert_relpath_O_insert,
["Pi"] = path_actions.insert_abspath_i_insert,
["PI"] = path_actions.insert_abspath_I_insert,
["Pa"] = path_actions.insert_abspath_a_insert,
["PA"] = path_actions.insert_abspath_A_insert,
["Po"] = path_actions.insert_abspath_o_insert,
["PO"] = path_actions.insert_abspath_O_insert,
["<leader>pi"] = path_actions.insert_relpath_i_visual,
["<leader>pI"] = path_actions.insert_relpath_I_visual,
["<leader>pa"] = path_actions.insert_relpath_a_visual,
["<leader>pA"] = path_actions.insert_relpath_A_visual,
["<leader>po"] = path_actions.insert_relpath_o_visual,
["<leader>pO"] = path_actions.insert_relpath_O_visual,
["<leader>Pi"] = path_actions.insert_abspath_i_visual,
["<leader>PI"] = path_actions.insert_abspath_I_visual,
["<leader>Pa"] = path_actions.insert_abspath_a_visual,
["<leader>PA"] = path_actions.insert_abspath_A_visual,
["<leader>Po"] = path_actions.insert_abspath_o_visual,
["<leader>PO"] = path_actions.insert_abspath_O_visual,
-- Additionally, there's normal mode mappings for the same actions:
-- ["<leader><leader>pi"] = path_actions.insert_relpath_i_normal,
-- ...
}
}
}
}

How to send signals/variables between a QDialog and Main Window

I am currently working on a project that involves graphing text file data into a pyqt graph and I have been running into problems with a subclass QDialog box. My goal is to have the QDialog box use a combox to choose between different data sets to graph (The code below shows the "steering angle" setting being chosen). The problem lies with how to make it so that when the Create Graph button is pressed (Found in the QDialog Class), it runs the createGraph(self): function in the main class. I dont know how to work classes that well so I dont know how to make this work.
If anyone has any pointers on either how to get this working, how to properly structure a PYQT Program or how to make it more efficient, I'm all ears.
Thank you for your time!
Main Window Code:
class MainWidget(QMainWindow):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
self.activateWindow()
self.raise_()
self.setupGraph()
self.dockcheck = 0
self.graphcheck = 0
self.setWindowTitle("Drag and Drop Test")
self.resize(1200, 800)
self.setAcceptDrops(True)
self.LBLDragAndDrop = QLabel("Drag And Drop Files Here")
self.LBLDragAndDrop.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
if self.graphcheck == 0:
self.setCentralWidget(self.LBLDragAndDrop)
self.path3 = "C:\\Users\\steph\\OneDrive\\Documents\\SAA Wing\\Coding\\Can Bus Data Reading\\Temporary Saves"
self.treeview = QTreeView()
self.treeview.setAnimated(True)
self.fileModel = QFileSystemModel()
self.fileModel.setRootPath(self.path3)
self.indexRoot = self.fileModel.index(self.fileModel.rootPath())
self.treeview.setModel(self.fileModel)
self.treeview.setRootIndex(self.fileModel.index(self.path3))
self.treeview.setColumnWidth(0, 250)
self.treeview.doubleClicked.connect(self.onSelectionChanged)
#self.treeview.doubleClicked.connect(self.openDialog)
####################################################################################################################
# Dialog Box
####################################################################################################################
def onSelectionChanged(self, index):
self.selectionPath = self.sender().model().filePath(index)
self.selectionFilename = (self.selectionPath.split("/")[-1])
IDList = ("ID 00d0","ID 00d1","ID 00d3","ID 00d4","ID 0140","ID 0141","ID 0360","ID 0361")
if self.selectionFilename in IDList:
if self.selectionFilename == "ID 00d0":
editDialog = Dialog00d0()
editDialog.exec_()
####################################################################################################################
# Graphing data
####################################################################################################################
def createGraph(self):
self.graphcheck = 1
if self.graphcheck == 1:
self.setCentralWidget(self.scroll_area)
################################################################################################################
# ID 00D0 Creating Graph
################################################################################################################
if self.selectionFilename == "ID 00d0":
self.df00d0 = pd.read_table(self.selectionPath, header=None , delim_whitespace=True, dtype=object)
self.df00d0.columns = ['Timestamp','ID',"B0","B1","B2","B3","B4","B5","B6","B7"]
self.df00d0.dropna(inplace=True)
self.SA = np.array([], dtype=float)
self.LatAcc = np.array([], dtype=float)
self.LonAcc = np.array([], dtype=float)
self.ComAcc = np.array([], dtype=float)
self.Time00d0 = np.array([], dtype=float)
self.Timestamp00d0 = np.array([], dtype=float)
############################################################################################################
# Getting Time Stamps
############################################################################################################
for item in self.df00d0['Timestamp']:
self.Time00d0 = np.append(self.Time00d0, datetime.fromtimestamp(float(item)).strftime("%H:%M:%S.%f")[:-4])
self.Timestamp00d0 = np.append(self.Timestamp00d0, float(item))
############################################################################################################
# Steering Angle Graph
############################################################################################################
if self.combobox00d0.currentText() == "Steering Angle":
SA_ = (((self.df00d0['B1']) + (self.df00d0['B0'])).apply(int, base=16) * 0.1)
for item in SA_:
if item > 6000:
self.SA = np.append(self.SA, round((item - 6553.6), 1))
else:
self.SA = np.append(self.SA, round(item))
y_value = self.SA
Here is the QDialog Box class code:
class Dialog00d0(QDialog):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
hlay = QHBoxLayout()
self.setLayout(self.layout)
self.setWindowTitle("Create Graph")
label = QLabel("Data Type")
self.combobox00d0 = QComboBox()
self.combobox00d0.addItem("Steering Angle")
self.combobox00d0.addItem("Latitudinal Acceleration")
self.combobox00d0.addItem("Longitudinal Acceleration")
self.combobox00d0.addItem("Combined Acceleration")
self.BTNCreateGraph = QPushButton("Create Graph")
self.BTNCancel = QPushButton("Cancel")
hlay.addWidget(self.BTNCreateGraph)
hlay.addWidget(self.BTNCancel)
self.layout.addWidget(label)
self.layout.addWidget(self.combobox00d0)
self.layout.addLayout(hlay)
self.BTNCreateGraph.clicked.connect("I need the self.creatGraph here")
self.BTNCancel.clicked.connect("self.close")
I imagine this will help you.
The pyqtSignal() argument tells you what information you want to carry.
In this case, I'm passing a text.
Good luck, I hope I helped.
import sys
from PyQt5.QtWidgets import QMainWindow, QDialog, QApplication
from PyQt5.QtWidgets import QPushButton, QVBoxLayout
from PyQt5 import QtCore, QtGui
class MainWidget(QMainWindow):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
button = QPushButton("Button to open dialog")
button.clicked.connect(self.button_clicked)
self.setCentralWidget(button)
self.show()
def button_clicked(self):
dlg = Dialog00d0()
dlg.signEmit.connect(self.createGraph)
dlg.exec()
def createGraph(self, _str):
print('Now Im here')
print(_str)
class Dialog00d0(QDialog):
signEmit = QtCore.pyqtSignal(str)
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.BTNCreateGraph = QPushButton("link to createGraph()")
self.layout.addWidget(self.BTNCreateGraph)
self.setLayout(self.layout)
self.BTNCreateGraph.clicked.connect(self.BTNCreateGraph_clicked)
def BTNCreateGraph_clicked(self):
self.signEmit.emit('But I passed by')
app = QApplication(sys.argv)
win = MainWidget()
app.exec()

Kivy getting values from Popup Window and use it at a Screen

Hi i am new to kivy and just started programming. So what i want to do is,once a user key in a valid date/time in the popup window, popup will close and will goes to a screen and create buttons. May i know how to pass the values get from getDay() which is dayoutput,timeoutput from popupwindow and transfer use it in another other class? and be able to use in the VariesTimeScreen?
Thank your for taking your time to help :)
class SetDateTime(Popup):
def getDay(self):
set_day = (self.ids.dayofmonth).text
set_month = (self.ids.month).text
set_year = (self.ids.year).text
set_hour = (self.ids.houroftime).text
set_minutes = (self.ids.minuteoftime).text
wrongtime = self.ids.wronginput_time
#Calculate Date and Time only when user input a valid number
if set_day.isdigit() and set_month.isdigit() and
set_year.isdigit()andset_hour.isdigit()
and set_minutes.isdigit():
try:
set_date = datetime.date(int(set_year),
int(set_month),int(set_day))
set_time = datetime.time(int(set_hour), int(set_minutes))
if not (set_date >= counttime.todaydate()):
wrongtime.text = "[color=#FF0000]Date is out of
range[/color]"
if not (set_time >= counttime.todaytime()):
wrongtime.text = "[color=#FF0000]Time is out of
range[/color]"
dayoutput = counttime.calculatedate(set_date)
timeoutput = set_hour + set_minutes
self.dismiss()
return dayoutput,timeoutput
except ValueError:
wrongtime.text = "[color=#FF0000]Please enter a valid
datetime.[/color]"
else:
wrongtime.text = "[color=#FF0000]Please enter a valid
date[/color]"
class VariesTimeScreen(Screen):
def __init__(self, **kwargs):
super(VariesTimeScreen, self).__init__(**kwargs)
a = '_icons_/mcdonald.png'
b = '_icons_/kfc.png'
c = '_icons_/subway.png'
Outlet_Store = [a,b,c]
layout = GridLayout(rows=1, spacing=100, size_hint_y=None,
pos_hint ={"top":.6,"x":0.2})
layout.bind(minimum_height=layout.setter('height'))
#Before the for loop there will be an if statement which is
the Day and Time i get from getDay() values. This part i'm
unsure how to retrieve the values from the SetDateTime Class
for image in Outlet_Store:
food_image = ImageButton(size_hint=(None, None),size=
(100,100),source=image)
layout.add_widget(food_image)
self.add_widget(layout)
One problem with your design is that the VariesTimeScreen is created very early in the App run, like when the GUI is created. So, the day and time from the SetDateTime Popup is not yet available. One way to handle this is to add an on_enter() method to the VariesTimeScreen to make any adjustments to the Screen at that time. To do that, I added Properties to the VariesTimeScreen:
class VariesTimeScreen(Screen):
day = StringProperty('None')
time = NumericProperty(0)
And add the on_enter() method to the VariesTimeScreen class:
def on_enter(self, *args):
print('day:', self.day, ', time:', self.time)
# make changes to the Screen
And then change the SetDateTime class slightly:
class SetDateTime(Popup):
def getDay(self):
set_day = (self.ids.dayofmonth).text
set_month = (self.ids.month).text
set_year = (self.ids.year).text
set_hour = (self.ids.houroftime).text
set_minutes = (self.ids.minuteoftime).text
wrongtime = self.ids.wronginput_time
# Calculate Date and Time only when user input a valid number
if set_day.isdigit() and set_month.isdigit() and set_year.isdigit() and set_hour.isdigit() and set_minutes.isdigit():
try:
set_date = datetime.date(int(set_year),
int(set_month), int(set_day))
set_time = datetime.time(int(set_hour), int(set_minutes))
if not (set_date >= counttime.todaydate()):
wrongtime.text = "[color=#FF0000]Date is out of range[ / color]"
if not (set_time >= counttime.todaytime()):
wrongtime.text = "[color=#FF0000]Time is out of range[ / color]"
dayoutput = counttime.calculatedate(set_date)
timeoutput = set_hour + set_minutes
# get the VariesTimeScreen
varies_time = App.get_running_app().root.ids.screen_manager.get_screen('variestime_screen')
# set the day and time for the VariesTimeScreen
varies_time.day = dayoutput
varies_time.time = timeoutput
# switch to the VariesTimeScreen
App.get_running_app().change_screen('variestime_screen')
# dismiss Popup
self.dismiss()
except ValueError:
wrongtime.text = "[color=#FF0000]Please enter a valid datetime.[ / color]"
else:
wrongtime.text = "[color=#FF0000]Please enter a valid date[ / color]"
The only changes are to set the day and time in the VariesTimeScreen, and to actually switch to the VariesTimeScreen. The switch to the VariesTimeScreen doesn't have to happen there, once the day and time are set, the on_enter() method will get called whenever it becomes the current Screen.

Libreoffice Calc run macro with HYPERLINK

I'm trying to use hyperlinks instead of buttons to run Basic macros. It seems to be more natural to me because hyperlinks are directly connected to a cell and buttons are not.
I'm using the following Formula:
=HYPERLINK("vnd.sun.star.script:Standard.Module1.Test?language=Basic&location=document";"Check")
It should call the Subroutine Test placed in the document's macros under Standard.Module1 and display the Text 'Check' in the Cell it is written.
This works absolutely fine with libreoffice 3.6.1.2 but it doesn't work at all with version 4.1.4.2. I can't see any errors it just happens nothing at all. I tried to simply click the Hyperlink and also to hold CTRL and click it. Same result - nothing.
When I use a button the macro works as expected.
Does anyone know how to solve this problem?
This seems to be a bug in Calc. The protocol vnd.sun.star.script runs in hyperlink URLs in Writer still in version 4.2. But in Calc it runs not.
As a workaround you could have the following function attached to the sheet event "Double click". Then the macro runs if you double click the cell with the =HYPERLINK formula.
The last two versions are the results of my first ideas. I will let them in the answer because of comprehensibility reasons. But this last version is the best workaround in my opinion. It will closest work like the original vnd.sun.star.script: URL.
public function Doubelclicked(target) as Boolean
if left(target.formula, 32) = "=HYPERLINK(""vnd.sun.star.script:" then
sFormulaHyperlink = target.formula
sMacroURLRaw = mid(sFormulaHyperlink, 13, instr(13, sFormulaHyperlink, ";") - 13)
target.formula = "=""" & sMacroURLRaw
sMacroURL = target.string
target.formula = sFormulaHyperlink
oDisp = createUnoService("com.sun.star.frame.DispatchHelper")
dim args(0) as new com.sun.star.beans.PropertyValue
args(0).Name = "URL"
args(0).Value = sMacroURL
oFrame = ThisComponent.CurrentController.Frame
oDisp.executeDispatch(oFrame, sMacroURL, "", 0, args)
end if
Doubelclicked = false
end function
Here are the previous versions:
public function Doubelclicked(target) as Boolean
if left(target.formula, 32) = "=HYPERLINK(""vnd.sun.star.script:" then
sMacroURL = mid(target.formula, 13, instr(13, target.formula, chr(34))-13)
oDisp = createUnoService("com.sun.star.frame.DispatchHelper")
oFrame = ThisComponent.CurrentController.Frame
oDisp.executeDispatch(oFrame, sMacroURL, "", 0, Array())
end if
Doubelclicked = false
end function
With this it is not possible to pass parameters in the macro URL. But if it only is the goal to get the address of the cell from which the macro was called, then this is possible because we have the target of the double click. So i have updated my workaround.
public function Doubelclicked(target) as Boolean
if left(target.formula, 32) = "=HYPERLINK(""vnd.sun.star.script:" then
lStartLocation = instr(13, target.formula,"&location=")
if lStartLocation > 0 then
lEndLocation = instr(lStartLocation + 1, target.formula,"&")
if lEndLocation = 0 then lEndLocation = instr(lStartLocation + 1, target.formula,"""")
sMacroURL = mid(target.formula, 13, lEndLocation - 13)
'msgbox sMacroURL
oDisp = createUnoService("com.sun.star.frame.DispatchHelper")
dim args(2) as new com.sun.star.beans.PropertyValue
args(0).Name = "TargetAddress"
args(0).Value = target.AbsoluteName
oFrame = ThisComponent.CurrentController.Frame
oDisp.executeDispatch(oFrame, sMacroURL, "", 0, args)
end if
end if
Doubelclicked = false
end function
Greetings
Axel

zend router optimization

How can I optimize all of these routes into one. As we do in .htaccess file.
routes.addemails.type = "Zend_Controller_Router_Route_Regex"
routes.addemails.route = "campaign/email/add"
routes.addemails.defaults.module = campaignManagement
routes.addemails.defaults.controller = Email
routes.addemails.defaults.action = add
routes.updateEmail.type = "Zend_Controller_Router_Route_Regex"
routes.updateEmail.route = "campaign/email/edit/?([a-zA-Z0-9_-]+)?"
routes.updateEmail.defaults.module = campaignManagement
routes.updateEmail.defaults.controller = Email
routes.updateEmail.defaults.action = edit
routes.updateEmail.map.key = 1
routes.delEmail.type = "Zend_Controller_Router_Route_Regex"
routes.delEmail.route = "campaign/email/delete/?([a-zA-Z0-9_-]+)?"
routes.delEmail.defaults.module = campaignManagement
routes.delEmail.defaults.controller = Email
routes.delEmail.defaults.action = delete
routes.delEmail.map.id = 1
I've not set up a route using a config file, but at a glance try:
routes.emails.route = "campaign/email/(add|edit|delete)/?([a-zA-Z0-9_-]+)?"
routes.emails.map.action = 1
routes.emails.map.id = 2
I am assuming that the map.* are the variables in the url (so action is the first bit of regex, with id being the second bit of regex. Correct me if I'm wrong).