Related
I'm working on a basic game with python, but the system gives an error
impostors.x = new_x_pos
AttributeError: 'list' object has no attribute 'x'
Below is my code, can anyone tell me what I'm doing wrong? I've checked very carefully but still can't find the error, Since I'm a newbie, I don't have much experience so I hope you guys can help me
import pgzrun
import random
FONT_COLOR = (255, 255, 255) #màu RGB
WIDTH = 1300
HEIGHT = 700
CENTER_X = WIDTH / 2
CENTER_Y = HEIGHT / 2
CENTER = (CENTER_X, CENTER_Y)
START_SPEED = 10
COLORS = ["orange", "blue"]
current_level = 1
final_level = 5
game_over = False
game_complete = False
impostors = []
animation = []
def draw():
global impostors,current_level,game_over,game_complete
screen.clear()
screen.blit("dark",(0,0))
if game_over:
display_message("Game Over", "Press Space to play again")
elif game_complete:
display_message("You win", "Press Space to play again")
else:
for im in impostors:
im.draw()
def update():
global impostors,current_level,game_over,game_complete
if len(impostors) == 0:
impostors = make_impostors(current_level)
if (game_over or game_complete) and keyboard.space:
impostors = []
current_level = 1
game_complete = False
game_over = False
def make_impostors(number_of_impostors):
colors_to_create = get_colors_to_create(number_of_impostors)
new_impostors = create_impostors(colors_to_create)
layout_impostors(new_impostors)
animate_impostors(new_impostors)
return new_impostors
def get_colors_to_create(number_of_impostors):
colors_to_create = ["red"]
for i in range(0,number_of_impostors):
random_color = random.choice(COLORS)
colors_to_create.append(random_color)
return colors_to_create
def create_impostors(colors_to_create):
new_impostors = []
for color in colors_to_create:
impostor = Actor(color + "-im")
new_impostors.append(impostors)
return new_impostors
def layout_impostors(impostors_to_layout):
number_of_gaps = len(impostors_to_layout) + 1
gap_size = WIDTH/number_of_gaps
random.shuffle(impostors_to_layout)
for index, impostor in enumerate(impostors_to_layout):
new_x_pos = (index + 1)*gap_size
impostor.x = new_x_pos
def animation_impostors(impostors_to_animate):
for impostors in impostors_to_animate:
duration = START_SPEED - current_level
impostors.anchor = ("center", "bottom")
animation = animation(impostors, duration = duration, on_finished = handle_game_over, y = HEIGHT)
animations.append(animation)
def handle_game_over():
global game_over
game_over = True
def on_mouse_down(pos):
global impostors, current_level
for impostors in impostors:
if impostors.collidepoint(pos):
if "red" in impostors.image:
red_impostor_click()
else:
handle_game_over()
def red_impostor_click():
global current_level, impostors, animation, game_complete
stop_animations(animations)
if current_level == final_level:
game_complete = True
else:
current_level = current_level + 1
impostors = []
animations = []
def stop_animations(animations_to_stop):
for animation in animations_to_stop:
if animation.running:
animation.stop()
def display_message(heading_text, sub_heading_text):
screen.draw.text(heading_text, fontsize = 60, center = CENTER, color = FONT_COLOR)
screen.draw.text(sub_heading_text,
fontsize = 30,
center = (CENTER_X, CENTER_Y + 30),
color = FONT_COLOR)
pgzrun.go()
The problem is the loop for impostors in impostors:. Rename the loop variable to impostor:
def on_mouse_down(pos):
global impostors, current_level
for impostor in impostors:
if impostor.collidepoint(pos):
if "red" in impostors.image:
red_impostor_click()
else:
handle_game_over()
I'm just starting with python 3, I've made 3 scripts which do what I want them to do and now I'm trying to include them in a very basic GUI that I made with tinker.
I've joined my 3 scripts into a single file and made a function of each of them
Basically I'd like to run this or that function when I click on a button in the frame.
The problem is that of course I d'ont know how to do it, can someone point me in the right direction ?
Thanks for the help.
from tkinter import *
from datetime import *
import time
def c60duree(delta):
(h, r) = divmod(delta.seconds, 3600)
(m, s) = divmod(r, 60)
return "%s%02d:%02d:%02d" % (
"%d jour(s) " % delta.days if delta.days > 0 else "",
h,
m,
s,
)
def code60():
saisie=0
c60=[[],[]]
while saisie != "X":
c60d=datetime.now()
print ("Code 60 activé à ", c60d.strftime("%H:%M:%S"))
saisie=input("Tapez entree pour la fin du code 60, X pour sortir : ")
c60f=datetime.now()
print("Debut ", c60d.strftime("%H:%M:%S"))
print("Fin ", c60f.strftime("%H:%M:%S"))
c60x=c60f-c60d
print("Duree ", c60duree(c60x))
print("-------------")
c60[0].append(c60d)
c60[1].append(c60f)
#del(c60[0],[-1])
#del(c60[1],[-1])
#return
def relais():
rel=[[],[],[],[],[]]
print("Relais pilote demarré ")
relh=datetime.now()
relv=input("Quelle voiture ? ")
relp=input("Quel pilote repart ? ")
rele=input("Quantité d'essence ? ")
input("Tapez entrée à la sortie des stands ")
rels=datetime.now()
rel[0].append(relh), rel[1].append(relv), rel[2].append(relp), rel[3].append(rele), rel[4].append(rels)
print("Dureé ", rels-relh)
print(*rel)
def essence():
ess=[[],[],[],[]]
print("Ravitaillement essence demarré ")
essh=datetime.now()
essv=input("Quelle voiture ? ")
essp=input("Quel pilote ? ")
essq=input("Combien de litres ? ")
ess[0].append(essh), ess[1].append(essv), ess[2].append(essp), ess[3].append(essq)
print(*ess)
fenetre = Tk()
fenetre['bg']='grey'
# frame 1
Frame1 = Frame(fenetre, bg="yellow", borderwidth=1, relief=GROOVE)
Frame1.pack(side=LEFT, padx=5, pady=5)
# frame 2
Frame2 = Frame(fenetre, bg="green", borderwidth=1, relief=GROOVE)
Frame2.pack(side=LEFT, padx=5, pady=5)
# frame 3
Frame3 = Frame(fenetre, bg="red", borderwidth=1, relief=GROOVE)
Frame3.pack(side=LEFT, padx=5, pady=5)
# Ajout de labels
Label(Frame1, text="Essence").pack(padx=300, pady=100)
Label(Frame2, text="Relais").pack(padx=300, pady=100)
Label(Frame3, text="C60").pack(padx=300, pady=100)
If you want to continue using Labels, you can bind a function to them like this:
# Ajout de labels
label1 = Label(Frame1, text="Essence")
label1.bind("<Button-1>", lambda event: essence())
label1.pack(padx=300, pady=100)
label2 = Label(Frame2, text="Relais")
label2.bind("<Button-1>", lambda event: relais())
label2.pack(padx=300, pady=100)
label3 = Label(Frame3, text="C60")
label3.bind("<Button-1>", lambda event: code60())
label3.pack(padx=300, pady=100)
I've had to give the labels each a name so I could add the binding. The bind method takes a key and a function. The key I've given is Button-1, which is the left mouse button. Therefore when you click on the label the function is run. When you bind a function, and extra argument called event is added. For this example we don't need event, so I've used lambda event: to essentially ignore it and call the function like normal.
Another way you could do this is with buttons:
# Ajout de labels
Button(Frame1, text="Essence", command = essence).pack(padx=300, pady=100)
Button(Frame2, text="Relais", command = relais).pack(padx=300, pady=100)
Button(Frame3, text="C60", command = code60).pack(padx=300, pady=100)
This is a lot more straightforward but looks different to a Label.
EDIT
To make the text appear in the GUI, you could do something like this:
def essenceResult(ess, ent1, ent2, ent3):
essh=datetime.now()
essv = ent1.get()
essp = ent2.get()
essq = ent3.get()
ess[0].append(essh), ess[1].append(essv), ess[2].append(essp), ess[3].append(essq)
resultLabel = Label(Frame4, text = str(ess))
resultLabel.grid(row = 5, column = 0, columnspan = 2)
def essence():
print("yr")
Frame4.grid(row = 1, column = 0)
ess=[[],[],[],[]]
Label1 = Label(Frame4, text = "Ravitaillement essence demarré ")
Label1.grid(row = 0, column = 0, columnspan = 2)
essvLabel = Label(Frame4, text = "Quelle voiture ? ")
essvEntry = Entry(Frame4)
essvLabel.grid(row = 1, column = 0)
essvEntry.grid(row = 1, column = 1)
esspLabel = Label(Frame4, text = "Quel pilote ? ")
esspEntry = Entry(Frame4)
esspLabel.grid(row = 2, column = 0)
esspEntry.grid(row = 2, column = 1)
essqLabel = Label(Frame4, text = "Combien de litres ? ")
essqEntry = Entry(Frame4)
essqLabel.grid(row = 3, column = 0)
essqEntry.grid(row = 3, column = 1)
submitButton = Button(Frame4, text = "Submit", command = lambda: essenceResult(ess, essvEntry, esspEntry, essqEntry))
submitButton.grid(row = 4, column = 0, columnspan = 2)
fenetre = Tk()
fenetre['bg']='grey'
# frame 1
Frame1 = Frame(fenetre, bg="yellow", borderwidth=1, relief=GROOVE)
Frame1.grid(row = 0, column = 0, padx=5, pady=5)
# frame 2
Frame2 = Frame(fenetre, bg="green", borderwidth=1, relief=GROOVE)
Frame2.grid(row = 0, column = 1, padx=5, pady=5)
# frame 3
Frame3 = Frame(fenetre, bg="red", borderwidth=1, relief=GROOVE)
Frame3.grid(row = 0, column = 2, padx=5, pady=5)
Frame4 = Frame(fenetre)
Frame4 is used to show the things for essence, but is not displayed until the user presses the button. The inputs have been replaced with a label for the question and an entry for the user to put their answer. Then when they press submit, the essenceResult function adds a label with what the print function used to show.
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
-------------------------------Solved(Partially)----------------------------------------
My problem is that when I try to display multiple images on the canvas using PIL, I end up with only the last image.
All the images have slightly different characteristics(angle offset). Also the having a plethora of entries, I have to use a loop for sure. Also I'll need to use PIL(tkinter objects not possible) for the angle offset feature.
Here is the code;
#!/usr/bin/python
# Filename: weather_sim.py
import os
import tkinter as tk
import h5py as hp
import numpy as np
import ntpath as ntp
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename
def path_leaf(path):
head, tail = ntp.split(path)
return tail or ntp.basename(head)
class CoordFind:
def __init__(self):
self.LatPx = 0
self.LonPx = 0
def find_px(self, Lat, Lon):
self.LatPx = (Lat - LatN)/LatLc
self.LonPx = (Lon - LonW)/LonLc
class PlottingGUI(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.coord = CoordFind()
self.root = parent
self.root.wm_title("-|-|-|-|||Wind Vector Plotter|||-|-|-|-")
self.root.resizable(False, False)
self.path = "None Selected"
self.HaM = 0
self.Lat = 0
self.Lon = 0
self.WiD = 0
self.WiS = 0
self.fr = tk.Frame(self.root, width = (width+20), height = (height+20), bd = 2)
self.fr.grid(row = 1, column = 0)
self.frBro = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frBro.grid(row = 0, column = 0)
self.frHi = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frHi.grid(row = 2, column = 0)
self.cv = tk.Canvas(self.fr, width = width, height = height, background = "white", bd = 0, relief = tk.SUNKEN)
self.cv.grid(row = 0, column = 0)
self.cv.create_image(1, 1, anchor = "nw", image = photo)
self.broButton = tk.Button(self.frBro, text = "Browse Dsets", command = self.analyseDset, height = 3, width = 16, bg = "yellow")
self.broButton.grid(row = 0, column = 0, padx = 20)
self.selFile = tk.Label(self.frBro, text = self.path)
self.selFile.grid(row = 0, column = 1)
self.caution = tk.Label(self.frHi, text = "Optional use. Warning!!, May lead to lags in program", fg = "red")
self.caution.grid(row = 0, column = 1)
self.shoRedBut = tk.Button(self.frHi, text = "Show H1", command = self.show_barbs1().__next__, height = 3, width = 16, bg = "#FF0000", fg = "white", activebackground="#E533B5")
self.shoRedBut.grid(row = 1, column = 0, padx = 7, pady = 2)
self.shoGrnBut = tk.Button(self.frHi, text = "Show H2", command = self.show_barbs2().__next__, height = 3, width = 16, bg = "#00B400", fg = "white", activebackground="#B5E533")
self.shoGrnBut.grid(row = 1, column = 1, padx = 7, pady = 2)
self.shoBluBut = tk.Button(self.frHi, text = "Show H3", command = self.show_barbs3().__next__, height = 3, width = 16, bg = "#0000FF", fg = "white", activebackground="#33B5E5")
self.shoBluBut.grid(row = 1, column = 2, padx = 7, pady = 2)
self.desc1 = tk.Label(self.frHi, text = "100-250 hPa", fg = "white", bg = "black")
self.desc1.grid(row = 2, column = 0)
self.desc2 = tk.Label(self.frHi, text = "250-350 hPa", fg = "white", bg = "black")
self.desc2.grid(row = 2, column = 1)
self.desc3 = tk.Label(self.frHi, text = "350-700 hPa", fg = "white", bg = "black")
self.desc3.grid(row = 2, column = 2)
def analyseDset(self):
self.path = askopenfilename(filetypes = (("Dataset files", "*.h5")
,("All files", "*.*") ))
self.jfname = path_leaf(self.path)
self.selFile = tk.Label(self.frBro, text = self.jfname)
self.selFile.grid(row = 0, column = 1)
self.extDset()
def extDset(self):
hf = hp.File(self.path, 'r')
HaM = hf.get('HEIGHT_ASSIGNMENT_METHOD')
Lat = hf.get('Latitude')
Lon = hf.get('Longitude')
WiD = hf.get('WIND_DIRECTION')
WiS = hf.get('WIND_SPEED')
self.HaM = np.array(HaM)
self.Lat = np.array(Lat)/100
self.Lon = np.array(Lon)/100
self.WiD = np.array(WiD)
self.WiS = np.array(WiS)
self.BrbImR = np.empty((self.HaM.shape[0],1))
self.BrbImB = np.empty((self.HaM.shape[0],1))
def show_barbs1(self):
self.coord = CoordFind()
script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Red_Barbs\icons8-wind-speed-43-47-50.png'))
w, h = im.size
im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im = ImageTk.PhotoImage(im.rotate(45))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 0:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImR[i] = self.cv.create_image(x, y, image = vec_im)
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImR[i], state = tk.NORMAL)
self.shoRedBut.configure(text = "Showing H1")
yield
def show_barbs2(self):
self.coord = CoordFind()
BrbImG = np.empty((self.HaM.shape[0],1))
script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Green_Barbs\icons8-wind-speed-43-47-50.png'))
w, h = im.size
im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 1:
vec_im = ImageTk.PhotoImage(im.rotate(self.WiD[i]))
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
BrbImG[i] = self.cv.create_image(x, y, image = vec_im)
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(BrbImG[i], state = tk.NORMAL)
self.shoGrnBut.configure(text = "Showing H2")
yield
def show_barbs3(self):
self.coord = CoordFind()
script_dir = os.path.dirname(os.path.abspath(__file__))
im = Image.open(os.path.join(script_dir, 'Blue_Barbs\icons8-wind-speed-43-47-50.png'))
w, h = im.size
im = im.resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im = ImageTk.PhotoImage(im.rotate(180))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 2:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImB[i] = self.cv.create_image(x, y, image = vec_im)
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImB[i], state = tk.NORMAL)
self.shoBluBut.configure(text = "Showing H3")
yield
if __name__ == "__main__":
root = tk.Tk()
backmap = "Map.png"
photo = ImageTk.PhotoImage(file = backmap)
width = photo.width()
height = photo.height()
LatN = 69.5
LatS = -69.3
LonE = 148.9
LonW = 1.0
LatLc = (LatS - LatN)/height
LonLc = (LonE - LonW)/width
app = PlottingGUI(root)
root.mainloop()
The output currently is this;(For the green arrows as that is what I have tested on)
This is what I want;(But with different angles)
I am using Python 3.6 on Windows 10.
Thanks in advance!!
P.S.: Also there is another problem if someone can help me with that. I would like to be able to choose a particular image based on a range factor(Wind Speed) by doing like a switch-case(or if-elif-else) procedure if possible. But when I try to do that it says "No such File or Directory". I may put it in another Question though.
-------------------------------Solved(Till this point)---------------------------------
EDIT: Solved the problem of displaying multiple arrows according to
choice and at different angles.
Here's the code;
#!/usr/bin/python
# Filename: weather_sim.py
import os
import tkinter as tk
import h5py as hp
import numpy as np
import ntpath as ntp
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfilename
def path_leaf(path):
head, tail = ntp.split(path)
return tail or ntp.basename(head)
class CoordFind:
def __init__(self):
self.LatPx = 0
self.LonPx = 0
def find_px(self, Lat, Lon):
self.LatPx = (Lat - LatN)/LatLc
self.LonPx = (Lon - LonW)/LonLc
class PlottingGUI(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.coord = CoordFind()
self.root = parent
self.root.wm_title("-|-|-|-|||Wind Vector Plotter|||-|-|-|-")
self.root.resizable(False, False)
self.path = "None Selected"
self.HaM = 0
self.Lat = 0
self.Lon = 0
self.WiD = 0
self.WiS = 0
self.ima = []
self.fr = tk.Frame(self.root, width = (width+20), height = (height+20), bd = 2)
self.fr.grid(row = 1, column = 0)
self.frBro = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frBro.grid(row = 0, column = 0)
self.frHi = tk.Frame(self.root, width = (width+20), height = 50, bd = 2)
self.frHi.grid(row = 2, column = 0)
self.cv = tk.Canvas(self.fr, width = width, height = height, background = "white", bd = 0, relief = tk.SUNKEN)
self.cv.grid(row = 0, column = 0)
self.cv.create_image(1, 1, anchor = "nw", image = photo)
self.broButton = tk.Button(self.frBro, text = "Browse Dsets", command = self.analyseDset, height = 3, width = 16, bg = "yellow")
self.broButton.grid(row = 0, column = 0, padx = 20)
self.selFile = tk.Label(self.frBro, text = self.path)
self.selFile.grid(row = 0, column = 1)
self.caution = tk.Label(self.frHi, text = "Optional use. Warning!!, May lead to lags in program", fg = "red")
self.caution.grid(row = 0, column = 1)
self.shoRedBut = tk.Button(self.frHi, text = "Show H1", command = self.show_barbs1().__next__, height = 3, width = 16, bg = "#FF0000", fg = "white", activebackground="#E533B5")
self.shoRedBut.grid(row = 1, column = 0, padx = 7, pady = 2)
self.shoGrnBut = tk.Button(self.frHi, text = "Show H2", command = self.show_barbs2().__next__, height = 3, width = 16, bg = "#00B400", fg = "white", activebackground="#B5E533")
self.shoGrnBut.grid(row = 1, column = 1, padx = 7, pady = 2)
self.shoBluBut = tk.Button(self.frHi, text = "Show H3", command = self.show_barbs3().__next__, height = 3, width = 16, bg = "#0000FF", fg = "white", activebackground="#33B5E5")
self.shoBluBut.grid(row = 1, column = 2, padx = 7, pady = 2)
self.desc1 = tk.Label(self.frHi, text = "100-250 hPa", fg = "white", bg = "black")
self.desc1.grid(row = 2, column = 0)
self.desc2 = tk.Label(self.frHi, text = "250-350 hPa", fg = "white", bg = "black")
self.desc2.grid(row = 2, column = 1)
self.desc3 = tk.Label(self.frHi, text = "350-700 hPa", fg = "white", bg = "black")
self.desc3.grid(row = 2, column = 2)
def analyseDset(self):
self.path = askopenfilename(filetypes = (("Dataset files", "*.h5")
,("All files", "*.*") ))
self.jfname = path_leaf(self.path)
self.selFile = tk.Label(self.frBro, text = self.jfname)
self.selFile.grid(row = 0, column = 1)
self.extDset()
def extDset(self):
hf = hp.File(self.path, 'r')
HaM = hf.get('HEIGHT_ASSIGNMENT_METHOD')
Lat = hf.get('Latitude')
Lon = hf.get('Longitude')
WiD = hf.get('WIND_DIRECTION')
WiS = hf.get('WIND_SPEED')
self.HaM = np.array(HaM)
self.Lat = np.array(Lat)/100
self.Lon = np.array(Lon)/100
self.WiD = np.array(WiD)
self.WiS = np.array(WiS)
self.BrbImR = np.empty((self.HaM.shape[0],1))
self.BrbImG = np.empty((self.HaM.shape[0],1))
self.BrbImB = np.empty((self.HaM.shape[0],1))
def barb_def(self, WiS):
if WiS < 1:
self.ima = "1.png"
elif WiS < 3:
self.ima = "2.png"
elif WiS < 8:
self.ima = "3.png"
elif WiS < 13:
self.ima = "4.png"
elif WiS < 18:
self.ima = "5.png"
elif WiS < 23:
self.ima = "6.png"
elif WiS < 28:
self.ima = "7.png"
elif WiS < 33:
self.ima = "8.png"
elif WiS < 38:
self.ima = "9.png"
elif WiS < 43:
self.ima = "10.png"
elif WiS < 48:
self.ima = "11.png"
elif WiS < 53:
self.ima = "12.png"
elif WiS < 58:
self.ima = "13.png"
elif WiS < 63:
self.ima = "14.png"
elif WiS < 68:
self.ima = "15.png"
elif WiS < 73:
self.ima = "16.png"
elif WiS < 78:
self.ima = "17.png"
elif WiS < 83:
self.ima = "18.png"
elif WiS < 88:
self.ima = "19.png"
elif WiS < 93:
self.ima = "20.png"
elif WiS < 98:
self.ima = "21.png"
elif WiS < 103:
self.ima = "22.png"
else:
self.ima = "23.png"
def show_barbs1(self):
self.coord = CoordFind()
vec_im = []
im = []
p = []
script_dir = os.path.dirname(os.path.abspath(__file__))
for i in range(0, self.HaM.shape[0]):
self.barb_def(self.WiS[i])
p.append("{}{}".format('Red_Barbs\\', self.ima))
im.append(Image.open(os.path.join(script_dir, p[i])))
w, h = im[i].size
im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i])))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 0:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImR[i] = self.cv.create_image(x, y, image = vec_im[i])
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImR[i], state = tk.NORMAL)
self.shoRedBut.configure(text = "Showing H1")
yield
def show_barbs2(self):
self.coord = CoordFind()
vec_im = []
im = []
p = []
script_dir = os.path.dirname(os.path.abspath(__file__))
for i in range(0, self.HaM.shape[0]):
self.barb_def(self.WiS[i])
p.append("{}{}".format('Green_Barbs\\', self.ima))
im.append(Image.open(os.path.join(script_dir, p[i])))
w, h = im[i].size
im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i])))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 1:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImG[i] = self.cv.create_image(x, y, image = vec_im[i])
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImG[i], state = tk.NORMAL)
self.shoGrnBut.configure(text = "Showing H2")
yield
def show_barbs3(self):
self.coord = CoordFind()
vec_im = []
im = []
p = []
script_dir = os.path.dirname(os.path.abspath(__file__))
for i in range(0, self.HaM.shape[0]):
self.barb_def(self.WiS[i])
p.append("{}{}".format('Blue_Barbs\\', self.ima))
im.append(Image.open(os.path.join(script_dir, p[i])))
w, h = im[i].size
im[i] = im[i].resize((int(w/2), int(h/2)), Image.ANTIALIAS)
vec_im.append(ImageTk.PhotoImage(im[i].rotate(self.WiD[i])))
for i in range(0, self.HaM.shape[0]):
if self.HaM[i] == 2:
self.coord.find_px(self.Lat[i], self.Lon[i])
x = self.coord.LonPx
y = self.coord.LatPx
self.BrbImB[i] = self.cv.create_image(x, y, image = vec_im[i])
while True:
for i in range(0, self.HaM.shape[0]):
self.cv.itemconfigure(self.BrbImB[i], state = tk.NORMAL)
self.shoBluBut.configure(text = "Showing H3")
yield
if __name__ == "__main__":
root = tk.Tk()
backmap = "Map.png"
photo = ImageTk.PhotoImage(file = backmap)
width = photo.width()
height = photo.height()
LatN = 69.5
LatS = -69.3
LonE = 148.9
LonW = 1.0
LatLc = (LatS - LatN)/height
LonLc = (LonE - LonW)/width
app = PlottingGUI(root)
root.mainloop()
But this ended up having a new problem. One set of coloured arrows is showing at a time but when I click the button to display another set it goes "Python stopped working because of some error" and then the shell restarts. Don't know what's the prob though.
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?