Saving real time data in Python - excel

I have a python interface of a software which stores data from the camera in excel. The software working is when I click Ready the camera starts recording and status shows(Running) and then when i click on the same tab it stops. NOw i want to write the current data in excel. Currently it is saving all the previous values.
It would be very helpful if i could get help on this as I am new to Python.
import wx
import wx.lib.activex
import csv
import comtypes.client
class EventSink(object):
def __init__(self, frame):
self.counter = 0
self.frame = frame
def DataReady(self):
self.counter +=1
self.frame.Title= "DataReady fired {0} times".format(self.counter)
class MyApp( wx.App ):
def OnClick(self,e):
rb_selection = self.rb.GetStringSelection()
if rb_selection == "WinCam":
data = self.gd.ctrl.GetWinCamDataAsVariant()
data = [[x] for x in data]
else:
p_selection = self.cb.GetStringSelection()
if p_selection == "Profile_X":
data = self.px.ctrl.GetProfileDataAsVariant()
data = [[x] for x in data]#csv.writerows accepts a list of rows where each row is a list, a list of lists
elif p_selection == "Profile_Y":
data = self.py.ctrl.GetProfileDataAsVariant()
data = [[x] for x in data]
**elif p_selection =="data_info":
while self.data18 ==1:
data= [self.data1,self.data2,self.data3,self.data4,self.data5,self.data6,self.data7,self.data8,self.data9,self.data10,self.data11,self.data12,self.data13,self.data14,self.data15,self.data16,self.data17,self.data18]
b=data
file = open('C:\\Users\\Namrata\\data.csv', 'w')
with file:
a = ['Clip Level a', 'Clip level b', 'Major','Minor','Mean','Eff_2W','Ellip','Orient','Crosshair','Xc','Yc','Centroid','Rc','ADC Peak','Exposure','image zoom','plateau uniformity']
zip(a,b)
out = csv.writer(file)
out.writerows(zip(a,b))
file.close()**
else:
datax = self.px.ctrl.GetProfileDataAsVariant()
datay = self.py.ctrl.GetProfileDataAsVariant()
data = [list(row) for row in zip(datax,datay)]#Makes a list of lists; X1 with Y1 in a list, X2 with Y2 in a list etc...
filename = self.ti.Value
with open(filename, 'w') as fp:
w = csv.writer(fp, delimiter=',')
w.writerows(data)
def __init__( self, redirect=False, filename=None ):
wx.App.__init__( self, redirect, filename )
self.frame = wx.Frame( parent=None, id=wx.ID_ANY,size=(1000,760), title='Python Interface to DataRay')
#Panel
p = wx.Panel(self.frame, wx.ID_ANY)
#Get Data
self.gd = wx.lib.activex.ActiveXCtrl(p, 'DATARAYOCX.GetDataCtrl.1')
#The methods of the object are available through the ctrl property of the item
self.gd.ctrl.StartDriver()
self.counter = 0
sink = EventSink(self.frame)
self.sink = comtypes.client.GetEvents(self.gd.ctrl, sink)
#Button Panel
bp = wx.Panel(parent=self.frame, id=wx.ID_ANY, size=(300, 400))
b1 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(280,25), pos=(20, 0),axID='DATARAYOCX.ButtonCtrl.1')
b1.ctrl.ButtonID =297
self.data18= b1.ctrl.GetParameter()
b1.ctrl.GetParameter()#Id's for some ActiveX controls must be set
b2 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5, 30),axID='DATARAYOCX.ButtonCtrl.1')
b2.ctrl.ButtonID =294
self.data1= b2.ctrl.GetParameter()
b3 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150,30),axID='DATARAYOCX.ButtonCtrl.1')
b3.ctrl.ButtonID =295
data2= b3.ctrl.GetParameter()
b4 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5,60),axID='DATARAYOCX.ButtonCtrl.1')
b4.ctrl.ButtonID =180
data3= b4.ctrl.GetParameter()
b5 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 60),axID='DATARAYOCX.ButtonCtrl.1')
b5.ctrl.ButtonID =181
self.data4= b5.ctrl.GetParameter()
b6 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5, 90),axID='DATARAYOCX.ButtonCtrl.1')
b6.ctrl.ButtonID =182
data5= b6.ctrl.GetParameter()
b7 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 90),axID='DATARAYOCX.ButtonCtrl.1')
b7.ctrl.ButtonID =95
data6= b7.ctrl.GetParameter()
b8 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5, 120),axID='DATARAYOCX.ButtonCtrl.1')
b8.ctrl.ButtonID =177
data7= b8.ctrl.GetParameter()
b9 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 120),axID='DATARAYOCX.ButtonCtrl.1')
b9.ctrl.ButtonID =179
data8= b9.ctrl.GetParameter()
b10 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5,150),axID='DATARAYOCX.ButtonCtrl.1')
b10.ctrl.ButtonID =302
data9= b10.ctrl.GetParameter()
b11= wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 150),axID='DATARAYOCX.ButtonCtrl.1')
b11.ctrl.ButtonID =171
data10= b11.ctrl.GetParameter()
b12 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5, 180),axID='DATARAYOCX.ButtonCtrl.1')
b12.ctrl.ButtonID =172
data11= b12.ctrl.GetParameter()
b13 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 180),axID='DATARAYOCX.ButtonCtrl.1')
b13.ctrl.ButtonID =298
data12= b13.ctrl.GetParameter()
b14 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5, 210),axID='DATARAYOCX.ButtonCtrl.1')
b14.ctrl.ButtonID =425
data13= b14.ctrl.GetParameter()
b15 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 210),axID='DATARAYOCX.ButtonCtrl.1')
b15.ctrl.ButtonID =183
data14= b15.ctrl.GetParameter()
b16 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(5, 240),axID='DATARAYOCX.ButtonCtrl.1')
b16.ctrl.ButtonID =409
data15= b16.ctrl.GetParameter()
b17 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(140,25), pos=(150, 240),axID='DATARAYOCX.ButtonCtrl.1')
b17.ctrl.ButtonID =301
data16= b17.ctrl.GetParameter()
b18 = wx.lib.activex.ActiveXCtrl(parent=bp,size=(280,25), pos=(5, 270),axID='DATARAYOCX.ButtonCtrl.1')
b18.ctrl.ButtonID =291
data17= b18.ctrl.GetParameter()
#Custom controls
t = wx.StaticText(bp, label="File:", pos=(5, 300))
self.ti = wx.TextCtrl(bp, value="C:\\Users\\Public\\Documents\\output.csv", pos=(30, 300), size=(170, -1))
self.rb = wx.RadioBox(bp, label="Data:", pos=(5, 330), choices=["Profile", "WinCam","Data Info"])
self.cb = wx.ComboBox(bp, pos=(5,380), choices=[ "Profile_X", "Profile_Y", "data_info","Both"])
self.cb.SetSelection(0)
myb = wx.Button(bp, label="Write", pos=(150,380))
myb.Bind(wx.EVT_BUTTON, self.OnClick)
myd = wx.Button(bp, label="Dialog", pos=(150,330))
myd.Bind(wx.EVT_BUTTON, self.OnClick)
#Pictures
pic = wx.lib.activex.ActiveXCtrl(parent=self.frame,size=(300,400),axID='DATARAYOCX.CCDimageCtrl.1')
tpic = wx.lib.activex.ActiveXCtrl(parent=self.frame,size=(300,400), axID='DATARAYOCX.ThreeDviewCtrl.1')
palette = wx.lib.activex.ActiveXCtrl(parent=self.frame,size=(10,250), axID='DATARAYOCX.PaletteBarCtrl.1')
#Profiles
self.px = wx.lib.activex.ActiveXCtrl(parent=self.frame,size=(300,300),axID='DATARAYOCX.ProfilesCtrl.1')
self.px.ctrl.ProfileID=22
self.py = wx.lib.activex.ActiveXCtrl(parent=self.frame,size=(300,300),axID='DATARAYOCX.ProfilesCtrl.1')
self.py.ctrl.ProfileID = 23
self.ax = wx.lib.activex.ActiveXCtrl(parent=self.frame,size=(150,360),axID='DATARAYOCX.getdataCtrl.1')
#Formatting
row1 = wx.BoxSizer(wx.HORIZONTAL)
row1.Add(window=bp,flag=wx.RIGHT, border=10)
row1.Add(pic)
row1.Add(window=tpic, flag=wx.LEFT, border=10)
row2 = wx.BoxSizer(wx.HORIZONTAL)
row2.Add(self.px, 0, wx.RIGHT, 100)# Arguments: item, proportion, flags, border
row2.Add(self.py)
col1 = wx.BoxSizer(wx.VERTICAL)
col1.Add(sizer=row1, flag=wx.BOTTOM, border=10)
col1.Add(sizer=row2, flag=wx.ALIGN_CENTER_HORIZONTAL)
self.frame.SetSizer(col1)
self.frame.Show()
if __name__ == "__main__":
app = MyApp()
app.MainLoop()

to save data in real time you can do this:
first create a wx.timer that fires constantly:
self.timer = wx.Timer(self)
self.timer.start(#here you have to specify the amount of milliseconds the timer sleep before fire again)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
then you create the OnTimer() function to store data in the excel file:
from openpyxl import load_workbook
def OnTimer(self, event):
data = #here you get your data
wb = load_workbook('path/to/yout/excel/file.xlsx')
sheet = wb.active()
#here you have to play with cells rows and cols by inserting data and saving,
#for more info go to the below link
openpyxl documentation

Related

one of my def variables is stuck at the same value

I am new to python and this website
*I am having difficulties understanding why I'm getting the same value from my Car.name function
class Car:
def __init__(self, name, price):
Car.name = name
Car.price = price
I have stored some cars data in the class
Lamborghini_Centenario = Car("Lamborghini Centenario", 2500000)
Rolls_Royce_Sweptail = Car("Roll's-Royce Sweptail", 12800000)
McLarenP1LM = Car("McLaren P1 LM", 3600000)
Koenigsigg = Car("Koenigsigg CCXR Trevita", 4800000)
Lykan_Hypersport = Car("Lykan Hypersport", 3400000)
Lamborghini_Veneno_Roadster = Car("Lamborghini Veneno Roadster", 4500000)
Aston_Martin_Valkyrie = Car("Aston Martin Valkyrie", 3200000)
Bugatti_Chiron = Car("Bugatti Chiron", 2700000)
Pagani_Huayra_BC = Car("Pagani Huayra BC", 2800000)
Ferrari_Sergio = Car("Ferrari Pininfarina\n Sergio", 3000000) <--.
|
#But when I try to get the name of a random car |
#Here is the code I used vvv (Carlist is not shown here) |
#b = random.choice(carlist) | ignore arrow not part of
#b.name | code(sorry couldn't come
#it only gets the name from the bottom of the car data area. --------+ up with a name)
#I have switched it up and have only been getting the bottom value
#it might be due to the turtle module .mainloop() function
here is the whole script
Thanks in advance
import random
import turtle
import os
import time
class Car:
def __init__(self, name, price):
Car.name = name
Car.price = price
higher_true = 0
lower_true = 0
lives1 = 1
score = 0
Lamborghini_Centenario = Car("Lamborghini Centenario", 2500000)
Rolls_Royce_Sweptail = Car("Roll's-Royce Sweptail", 12800000)
McLarenP1LM = Car("McLaren P1 LM", 3600000)
Koenigsigg = Car("Koenigsigg CCXR Trevita", 4800000)
Lykan_Hypersport = Car("Lykan Hypersport", 3400000)
Lamborghini_Veneno_Roadster = Car("Lamborghini Veneno Roadster", 4500000)
Aston_Martin_Valkyrie = Car("Aston Martin Valkyrie", 3200000)
Bugatti_Chiron = Car("Bugatti Chiron", 2700000)
Pagani_Huayra_BC = Car("Pagani Huayra BC", 2800000)
Ferrari_Sergio = Car("Ferrari Pininfarina\n Sergio", 3000000)
carlist = [Lamborghini_Centenario, Rolls_Royce_Sweptail, McLarenP1LM, Koenigsigg, Lykan_Hypersport, Lamborghini_Veneno_Roadster, Aston_Martin_Valkyrie, Bugatti_Chiron, Ferrari_Sergio, Pagani_Huayra_BC]
wn = turtle.Screen()
wn.screensize(1000, 500)
wn.title("Higher or Lower: Car Price Edition")
wn.setup(1050, 650, 0, 0)
Higher = turtle.Turtle()
Higher.penup()
style = ('Courier', 55, 'italic')
Higher.color('black')
Higher.goto(130, -300)
Higher.write('Higher', font=style, align='center')
Higher.hideturtle()
Or = turtle.Turtle()
Or.penup()
Or.color('black')
Or.goto(275, -300)
Or.write('or', font=style, align='center')
Or.hideturtle()
correct = turtle.Turtle()
correct.penup()
correct.color('green')
correct.hideturtle()
Lower = turtle.Turtle()
Lower.penup()
Lower.color('black')
Lower.goto(406, -300)
Lower.write('Lower', font=style, align='center')
Lower.hideturtle()
line = turtle.Turtle()
line.goto(0, 0)
line.shape('square')
line.shapesize(500, 0.5)
line.color('black')
Lives = turtle.Turtle()
Lives.penup()
Lives.color('black')
style = ('Courier', 60, 'italic')
Lives.goto(158, 260)
Lives.write('Lives:', font=style, align='center')
Lives.hideturtle()
Scores = turtle.Turtle()
Scores.penup()
Scores.color('black')
Scores.goto(-258, 260)
Scores.write('Score:', font=style, align='center')
Scores.hideturtle()
wn.addshape(os.path.expanduser("~/Downloads/Lamborghini_Centenario.gif"))
wn.addshape(os.path.expanduser("~/Downloads/RollsRoyceSweptail.gif"))
wn.addshape(os.path.expanduser("~/Downloads/McLaren-P1-LM.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Koenigsegg-CCRX-Trevita.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Lamborghini-Veneno-Roadster.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Aston-martin-Valkyrie.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Bugatti-Chiron.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Pagani-Huayra-BC.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Ferrari-Pininfarina-Sergio.gif"))
wn.addshape(os.path.expanduser("~/Downloads/Lykan-Hypersport.gif"))
BugattiChiron = turtle.Turtle()
BugattiChiron.penup()
BugattiChiron.shape(os.path.expanduser("~/Downloads/Bugatti-Chiron.gif"))
BugattiChiron.goto(-300, 0)
Carname = turtle.Turtle()
Carname.penup()
Carname.color('black')
Carname.goto(-300, -200)
style1 = ('Courier', 40, 'italic')
Carname.write("Bugatti Chiron", font=style1, align='center')
Carname.hideturtle()
def screenclick(x, y):
print(x, y)
if x in range(39, 227) and y in range(-290, -250):
higher_true + 1
wn.listen()
wn.onscreenclick(screenclick)
a = Bugatti_Chiron
b = random.choice(carlist)
bname = turtle.Turtle()
bname.penup()
bname.goto(275, -200)
bname.write(b.name, font=style1, align='center')
# problem ^^^^^^ is here(it's just giving the Car.name of Ferrari_Sergio)
while higher_true == 0:
wn.update
while higher_true == 1:
if b >= a:
score = score + 1
correct.write('Correct!', font=style, align='center')
time.sleep(1.5)
correct.clear()
You need to set attributes on the object and not on the class.
class Car:
def __init__(self, name, price):
self.name = name
self.price = price
Car.name will set a name attribute on the Car class. You would be able to access the name attribute from the Car class directly without using objects like Car.name.
Setting Car.name every time updates the name attribute of the Car class and it gets updated every time you create a Car object. Hence, it retains only the last value.

My python program works on Linux but not on Widows?

So my program compares images and deletes any that are the same, renaming the original to how many were deleted. This program works fine on my Linux (ubuntu) but when used on my Windows 8 laptop I get the error at the bottom, any advice is greatly appreciated.
PIL.UnidentifiedImageError: cannot identify image file 'C:\\Users\\Public\\Pictures\\Sample Pictures/desktop.ini'
(there is more to the error code if you need it, also I import os, send2trash, pil, shutil and tkinter to use with the script)
import os
from PIL import ImageChops, ImageDraw
import PIL.Image
import shutil
from send2trash import send2trash
from tkinter import *
root = Tk()
root.title("Cupcake 3.0")
paths = Entry(root, width = 50, borderwidth = 5)
paths.grid(row = 2, column =2, columnspan =3)
path = paths.get()
def add():
end_image = PIL.Image.new(mode = "RGB",size = (200, 70), color = "red")
end_image.save(paths.get() +"/zzz999.png")
files = os.listdir(paths.get())
files.sort()
image1 =files[0]
counter = 1
im1 = " "
for file in files:
original_file_name, file_ext = (os.path.splitext(file))
if delete == 0:
ofn, fe = (os.path.splitext(image1))
if image1 == file:
pass
elif image1 != file:
im1 = PIL.Image.open(paths.get() + "/" + image1).histogram() #the image to be compared too
im2 = PIL.Image.open(paths.get() + "/" + file).histogram()#file for comparison
if im1 == im2:
send2trash(paths.get() + "/" +file)
counter = counter +1
elif im1 != im2:
os.rename(paths.get() + "/" + image1, paths.get() + "/" + ofn + "_X" +str(counter)+ fe)
counter = 1
image1 = file
else:
print("something went wrong")
else:
addd = input("Enter in the text you wish to be added/removed (can not contain blank spaces): ").strip()
new_name = "{}{}{}".format(original_file_name, addd, file_ext).strip()
os.rename(path + "/" + file, path + "/" + new_name)
print("Job Complete")
send2trash(paths.get() + "/zzz999.png")
welcome = Label(root, text = "Welcome to Cupcake 3.0")
welcome.grid(row = 0, column =2, columnspan =3)
l1 = Label (root, text = "Please enter the path to your folder: ")
l1.grid(row = 1, column =2, columnspan =3)
paths = Entry(root, width = 50, borderwidth = 5)
paths.grid(row = 2, column =2, columnspan =3)
path = paths.get()
d = IntVar()
Radiobutton(root, text = "Add", variable = d, value = 1, anchor = W).grid(row = 3, column = 2, sticky = W)
Radiobutton(root, text = "Remove", variable = d, value = 2,anchor = W).grid(row = 4, column = 2, sticky = W)
def_question = d.get()
l2 = Label (root, text = "Enter text you want removed (leave blank if n/a): ").grid(row = 6, column = 2)
rem = Entry(root, width = 50, borderwidth = 5)
rem.grid(row = 7, column =2, columnspan =3)
remo=rem.get().strip()
de = IntVar()
c = Checkbutton(root, text = "Do you wish to delete duplicate files?", variable = de)
c.grid(row = 8, column =2, sticky = W)
delete = de.get()
def run():
#print(d.get())
#print(def_question)
if d.get() == 1:
add()
elif d.get() == 2:
remove()
else:
print("I don't understand your command")
def remove():
files = os.listdir(paths.get())
files.sort()
for file in files:
original_file_name, file_ext = (os.path.splitext(file))
#print(remo)
new_name = original_file_name.replace(rem.get(), "").strip()
os.rename(paths.get() + "/" + file, paths.get() + "/" + new_name)
print("Job Complete")
submit = Button(root, text = "Run", command =lambda: run())
submit.grid(row = 9, column =2)
root.mainloop()
"
Thats my entire program
Try to filter out the files which are not identified as images by PIL. Something like this might work for you
def image_filter(filename):
file_path = os.path.join(paths.get(), filename)
try:
im = PIL.Image.open(file_path)
im.verify()
im.close()
return True
except: # you can handle PIL.UnidentifiedImageError here
return False
def add():
...
files = os.listdir(path)
# filter out the files which are not images
files = list(filter(image_filter, files))
files.sort()
image1 = files[0]
...

Text Select and Text Headed Pyglet

I have a script that I'm working on, in Pyglet.In this application I wanted to insert a console and I took as an example "examples/text_input.py" from Pyglet's guide. I modified it and tried to adapt it to my use. The result is this:
import pyglet, pyperclip
from pyglet.gl import *
from pyglet import clock
from collections import OrderedDict
key = pyglet.window.key
class MainGame(pyglet.window.Window):
#VariableFrame
WDisplay, HDisplay = 1024, 576
Fullscreen = False
FPS = 60
Title = "test"
ConsoleVar = False
#VariableConsole
showFPS = False
showPOSITION = False
showENTITY = False
showINFO = False
showHELP = False
helpPAGE = 0
GAMEMODE = 0
GODMODE = False
def __init__(self, width=WDisplay, height=HDisplay, caption=Title, fullscreen=Fullscreen, *args, **kwargs):
super().__init__(width, height, caption, fullscreen, *args, **kwargs)
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.infoScreen = (screen.width, screen.height)
self.xDisplay = int(screen.width / 2 - self.width / 2)
self.yDisplay = int(screen.height / 2 - self.height / 2)
self.set_location(self.xDisplay, self.yDisplay)
self._load()
def _load(self):
self.mapInfo = OrderedDict()
pyglet.resource.add_font('graphics/fonts/pkmndp.ttf')
pyglet.resource.add_font('graphics/fonts/pkmndpb.ttf')
self.consoleClass = Console(self, '')
self.text_cursor = self.get_system_mouse_cursor('text')
self.focus = None
self.set_focus(self.consoleClass)
def update(self, dt):
if self.ConsoleVar:
self.consoleClass.update()
def on_draw(self):
pyglet.gl.glClearColor(1, 1, 1, 1)
self.clear()
if self.ConsoleVar:
for sprite in self.mapInfo :
self.mapInfo[sprite].draw()
def on_mouse_press(self, x, y, button, modifiers):
if self.ConsoleVar:
if self.focus:
self.focus.caret.on_mouse_press(x, y, button, modifiers)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if self.ConsoleVar:
if self.focus:
self.focus.caret.on_mouse_drag(x, y, dx, dy, buttons, modifiers)
def on_text(self, text):
if self.ConsoleVar:
if self.focus:
self.focus.caret.on_text(text)
def on_text_motion(self, motion):
if self.ConsoleVar:
if self.focus:
self.focus.caret.on_text_motion(motion)
def on_text_motion_select(self, motion):
if self.ConsoleVar:
if self.focus:
self.focus.caret.on_text_motion_select(motion)
def on_key_press(self, symbol, modifiers):
if symbol == key.F1 and modifiers & key.MOD_CTRL:
if self.ConsoleVar:
self.ConsoleVar = False
self.focus.document.text = ""
else:
self.ConsoleVar = True
self.focus.document.text = "/"
self.focus.caret.position = 1
if symbol == key.F2 and modifiers & key.MOD_CTRL:
if self.ConsoleVar:
self.ConsoleVar = False
self.focus.document.text = ""
else:
self.ConsoleVar = True
self.focus.caret.position = 0
if symbol == key.ENTER:
if self.ConsoleVar:
self.ConsoleVar = False
self.consoleClass.Enter()
if modifiers & key.MOD_CTRL and symbol == key.V:
if self.ConsoleVar:
self.consoleClass.Copy_Paste("paste")
if modifiers & key.MOD_CTRL and symbol == key.C:
if self.ConsoleVar:
self.consoleClass.Copy_Paste("copy")
def set_focus(self, focus):
if self.focus:
self.focus.caret.visible = False
self.focus.caret.mark = self.focus.caret.position = 1
self.focus = focus
if self.focus:
self.focus.caret.visible = True
self.focus.caret.mark = 1
self.focus.caret.position = len(self.focus.document.text)
class Console(object):
ComandConsole = []
def __init__(self, game, text):
self.game = game
self.groups = self.game.mapInfo
self.image = pyglet.resource.image("graphics/other/alpha.png")
self.alpha = self.image.get_region(x=32, y=64, width=32, height=32)
self.alpha.width = self.game.WDisplay
self.sprite = pyglet.sprite.Sprite(self.alpha)
self.sprite.opacity = 128
self.sprite.x, self.sprite.y = 0, 10
self.groups["bg"] = self.sprite
self.document = pyglet.text.document.UnformattedDocument(text)
self.document.set_style(0, len(self.document.text), dict(font_name = "Power Clear", font_size = 15, color=(255,255, 255, 255)))
font = self.document.get_font()
height = font.ascent - font.descent
self.layout = pyglet.text.layout.IncrementalTextLayout(self.document, self.game.WDisplay, height, multiline=False)
self.caret = pyglet.text.caret.Caret(self.layout)
self.groups["text"] = self.layout
self.layout.x = 20
self.layout.y = (self.alpha.height / 2 + self.sprite.y) - (self.layout.height / 2)
pad = 2
def hit_test(self, x, y):
return (0 < x - self.layout.x < self.layout.width and
0 < y - self.layout.y < self.layout.height)
def Copy_Paste(self, function):
if function == "copy":
pyperclip.copy('Hello world!')
if function == "paste":
paste = pyperclip.paste()
self.document.text = self.document.text + paste
self.game.focus.caret.position = self.game.focus.caret.mark = len(self.document.text)
def Enter(self):
if len(self.document.text) == 0:
pass
else:
if self.document.text[0] == "/":
if self.document.text == "/ciao":
print("ciao")
else:
print("errore comando")
else:
print(self.document.text)
self.document.text = ""
def update(self):
pass
if __name__ == "__main__":
window = MainGame()
pyglet.clock.schedule_interval(window.update, 1/window.FPS)
pyglet.app.run()
Now, I would like to be able to highlight some text in the console by pressing shift + left or right and, by pressing crtl + c, copy the selected text via pyperclip. How can I do?
Another question, always inherent. In the Console Class, I would like to create a rectangle above the console. In it, I would like to report some text on several lines (like a chat). The problem, more than anything else, is that I do not know how to write the text as soon as it reaches the limit of the rectangle.
Very last, now the console is called with crtl + F1 (and the symbol "/" is added) or with crtl + F2. However, I would like to activate it with the letters "U" and "T". The problem is that I do it, the console appears with the letters pressed to recall it. So how can I avoid it?

Why is Python writing to my CSV file from the second row onward?

I'm trying to create a list of values and later be able to read, sort and search them later. Although when I write to my csv file, it skips the first line and prints on the next.
I've looked all over for the solution internally and externally but nothing helps.
Here's my code:
from tkinter import *
import csv
window=Tk()
def show_entry_fields():
with open('shoplist.csv', 'a') as csvfile:
list = csv.writer(csvfile, delimiter=',', lineterminator='\n')
list.writerow([ "%s" % (e3.get()) "%s" % (e4.get()), "%s" % (e5.get())])
Button(window, text='Add', command=show_entry_fields).grid(row=3, column=3)
v = StringVar()
e3 = Entry(window)
e4 = Entry(window)
e5 = Entry(window)
e3.grid(row = 3, column = 1)
e4.grid(row = 4, column = 1)
e5.grid(row = 5, column = 1)
l3 = Label(window, text = "Name:")
l3.grid(row = 3, column = 0)
l4 = Label(window, text = "Location:")
l4.grid(row = 4, column = 0)
l5 = Label(window, text = "Rate /5:")
l5.grid(row = 5, column = 0)

Python 3 Graphical calculator "bool object is not callable" error

Below is my attempt at a graphical calculator using Python 3. All the number, cancel and equals buttons work as they should. The issue I have is that when the '+' or '-' buttons are pressed, I receive this error message: "TypeError: 'bool' object is not callable." I would greatly appreciate if anyone could shed some light onto what this error message refers to and means.
from tkinter import *
class functions():
def __init__(self):
self.cumulative = 0
self.input = 0;
self.new_value = True
self.calculation = False
self.operation = ""
self.operation = False
def numpress(self, num):
self.number_equals = False
nostring = display_screen.get()
no2 = str(num)
if self.new_value:
self.input = no2
self.new_value = False
else:
self.input = nostring + no2
self.display(self.input)
def calc_total(self):
self.number_equals = True
self.input = int(self.input)
if self.calculation == True:
self.addition_calc()
else:
self.total = int(display_screen.get())
def display(self, value):
display_screen.delete(0, END)
display_screen.insert(0, value)
def addition_calc(self):
if self.operation == "addition":
self.total += self.input
if self.operation == "subtraction":
self.cumulative -= self.input
self.new_value = True
self.calculation = False
self.display(self.total)
def operation(self, operation):
self.input = int(self.input)
if self.calculation:
self.calc_total()
elif not self.number_equals:
self.total = self.input
self.new_value = True
self.calculation = True
self.operation = operation
self.number_equals = False
def cancel(self):
self.number_equals = False
self.input = "0"
self.display(0)
self.new_value = True
self.total = 0
ops = functions()
root = Tk()
root.resizable(0,0)
frame = Frame(root)
frame.pack()
root.title("Calculator")
screen_num=StringVar()
bgcolour="#000"
fgcolour="#00FF00"
display_screen=Entry (frame, bd=10, insertwidth=1, font=30)
display_screen.pack( side =TOP)
topframe = Frame(root)
topframe.pack(side = TOP)
b1 = Button(topframe,padx=24, pady=8, bd =6, text = "1", fg="black",)
b1.pack(side = LEFT)
b1["command"] = lambda: ops.numpress(1)
b2 = Button(topframe,padx=24, pady=8, bd =6, text = "2", fg="black",)
b2.pack(side = LEFT)
b2["command"] = lambda: ops.numpress(2)
b3 = Button(topframe,padx=24, pady=8, bd =6, text = "3", fg="black",)
b3.pack(side = LEFT)
b3["command"] = lambda: ops.numpress(3)
frame1 = Frame(root)
frame1.pack(side = TOP)
b4 = Button(frame1,padx=24, pady=8, bd =6, text = "4", fg="black",)
b4.pack(side = LEFT)
b4["command"] = lambda: ops.numpress(4)
b5 = Button(frame1,padx=24, pady=8, bd =6, text = "5", fg="black",)
b5.pack(side = LEFT)
b5["command"] = lambda: ops.numpress(5)
b6 = Button(frame1,padx=24, pady=8, bd =6, text = "6", fg="black",)
b6.pack(side = LEFT)
b6["command"] = lambda: ops.numpress(6)
frame2 = Frame(root)
frame2.pack(side = TOP)
b7 = Button(frame2,padx=24, pady=8, bd =6, text = "7", fg="black")
b7.pack(side = LEFT)
b7["command"] = lambda: ops.numpress(7)
b8 = Button(frame2,padx=24, pady=8, bd =6, text = "8", fg="black")
b8.pack(side = LEFT)
b8["command"] = lambda: ops.numpress(8)
b9 = Button(frame2,padx=24, pady=8, bd =6, text = "9", fg="black")
b9.pack(side = LEFT)
b9["command"] = lambda: ops.numpress(9)
frame3=Frame(root)
frame3.pack(side=TOP)
button0=Button(frame3,padx=24, pady=8, bd=6, text="0", fg="black")
button0.pack(side=LEFT)
button0["command"] = lambda: ops.numpress(0)
command=Frame(root)
command.pack(side=TOP)
buttonPlus=Button(command,padx=24, pady=8, bd =6, text = "+", fg="black")
buttonPlus.pack(side=LEFT)
buttonPlus["command"] = lambda: ops.operation("addition")
buttonMinus=Button(command,padx=24, pady=8, bd =6, text = "-", fg="black")
buttonMinus.pack(side=LEFT)
buttonMinus["command"] = lambda: ops.operation("subtraction")
buttonCancel=Button(command,padx=24, pady=8, bd =6, text = "C", fg="black")
buttonCancel.pack(side=LEFT)
buttonCancel["command"] = ops.cancel
command1=Frame(root)
command1.pack(side=TOP)
buttonEquals=Button(command1,padx=24, pady=8, bd =6, text = "=", fg="black")
buttonEquals.pack(side=LEFT)
buttonEquals["command"] = ops.calc_total
root.mainloop()
In the functions class, you have both a method and an instance variable named operation. When your callback tries to call the method via ops.operation, it gets the instance variable instead, which, after __init__ has run, will be False. Instance variables "shadow" class variables (such as methods).
To fix this, change the name of either the method or the variable. Then you can refer to each one unambiguously.

Resources